JSON → PHP 配列コード

ツール概要:JSON → PHP 配列コード変換ツール

JSONデータをPHPの配列コードに変換するツールです。ネスト構造、日本語文字、特殊文字エスケープをサポートし、ワンクリックでJSONデータを形式規範のPHP配列コードに変換できます。設定ファイル、API Mockデータ、データベースシードファイルなどのシーンに適用されます。

JSON → PHP 配列コード変換ツールとは?

JSON → PHP 配列コード変換ツールはJSONとPHP array codeの変換を素早く行い、すぐ使える結果を出力します。

使い方

  1. JSONの内容を貼り付けるかパラメータを入力します。
  2. PHP array codeの出力形式を選び、オプションを調整します。
  3. 結果を確認してコピーまたはダウンロードします。

よくある利用シーン

  • JSON↔PHP array codeのフォーマット移行
  • JSONデータをPHP array codeのワークフローやコード生成に利用
  • 変換結果の仕様チェック

❓ よくある質問

Q1: 変換に失敗する/空になる?
A: JSONの入力が正しいか確認してください。

Q2: 出力が違って見える?
A: PHP array codeのルールに合わせて整形される場合があります。

Q3: 一括処理は?
A: 安定のため小分けにして処理してください。

✨ 主な機能

  • 🔄 完全変換:JSONデータを実行可能なPHP配列コードに変換
  • 🌐 多言語対応:日本語、中国語、特殊文字を正しく処理
  • 🎨 美しいフォーマット:読みやすいインデントと構造でコードを生成
  • 📋 ワンクリックコピー:生成されたPHPコードを直接コピーして使用可能
  • 🔧 エスケープ処理:特殊文字の自動エスケープとセキュリティ処理

📖 使用例

基本的なJSON変換

入力JSON:

{
  "name": "ツールミ",
  "version": "1.0.0",
  "features": [
    "JSON変換",
    "PHP配列生成",
    "コード自動生成"
  ],
  "config": {
    "debug": true,
    "port": 3000
  }
}

生成されるPHPコード:

<?php
$data = [
    'name' => 'ツールミ',
    'version' => '1.0.0',
    'features' => [
        'JSON変換',
        'PHP配列生成',
        'コード自動生成'
    ],
    'config' => [
        'debug' => true,
        'port' => 3000
    ]
];
?>

複雑なネスト構造

入力JSON:

{
  "users": [
    {
      "id": 1,
      "name": "田中太郎",
      "email": "[email protected]",
      "profile": {
        "age": 30,
        "city": "東京",
        "hobbies": ["読書", "映画鑑賞", "プログラミング"]
      }
    },
    {
      "id": 2,
      "name": "佐藤花子",
      "email": "[email protected]",
      "profile": {
        "age": 25,
        "city": "大阪",
        "hobbies": ["旅行", "料理"]
      }
    }
  ],
  "meta": {
    "total": 2,
    "page": 1,
    "per_page": 10
  }
}

生成されるPHPコード:

<?php
$data = [
    'users' => [
        [
            'id' => 1,
            'name' => '田中太郎',
            'email' => '[email protected]',
            'profile' => [
                'age' => 30,
                'city' => '東京',
                'hobbies' => [
                    '読書',
                    '映画鑑賞',
                    'プログラミング'
                ]
            ]
        ],
        [
            'id' => 2,
            'name' => '佐藤花子',
            'email' => '[email protected]',
            'profile' => [
                'age' => 25,
                'city' => '大阪',
                'hobbies' => [
                    '旅行',
                    '料理'
                ]
            ]
        ]
    ],
    'meta' => [
        'total' => 2,
        'page' => 1,
        'per_page' => 10
    ]
];
?>

🎯 応用シーン

1. 設定ファイル生成

アプリケーション設定ファイルの作成:

<?php
// config/app.php
return [
    'name' => 'ツールミアプリケーション',
    'env' => 'production',
    'debug' => false,
    'url' => 'https://www.toolmi.com',
    
    'database' => [
        'default' => 'mysql',
        'connections' => [
            'mysql' => [
                'driver' => 'mysql',
                'host' => 'localhost',
                'port' => 3306,
                'database' => 'toolmi_db',
                'username' => 'root',
                'password' => 'secret',
                'charset' => 'utf8mb4',
                'collation' => 'utf8mb4_unicode_ci'
            ]
        ]
    ],
    
    'cache' => [
        'default' => 'redis',
        'stores' => [
            'redis' => [
                'driver' => 'redis',
                'host' => 'localhost',
                'port' => 6379,
                'database' => 0
            ]
        ]
    ],
    
    'mail' => [
        'driver' => 'smtp',
        'host' => 'smtp.gmail.com',
        'port' => 587,
        'encryption' => 'tls',
        'username' => '[email protected]',
        'password' => 'email_password'
    ],
    
    'services' => [
        'stripe' => [
            'key' => 'pk_test_...',
            'secret' => 'sk_test_...'
        ],
        'aws' => [
            'key' => 'AKIAIOSFODNN7EXAMPLE',
            'secret' => 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
            'region' => 'ap-northeast-1'
        ]
    ]
];

2. API Mockデータ

テスト用のモックデータ生成:

<?php
// tests/fixtures/api_responses.php
return [
    'user_list' => [
        'data' => [
            [
                'id' => 1,
                'username' => 'tanaka_taro',
                'email' => '[email protected]',
                'first_name' => '太郎',
                'last_name' => '田中',
                'avatar' => 'https://example.com/avatars/1.jpg',
                'created_at' => '2024-01-15T10:30:00Z',
                'updated_at' => '2024-06-15T14:20:00Z',
                'status' => 'active',
                'roles' => ['user', 'editor']
            ],
            [
                'id' => 2,
                'username' => 'sato_hanako',
                'email' => '[email protected]',
                'first_name' => '花子',
                'last_name' => '佐藤',
                'avatar' => 'https://example.com/avatars/2.jpg',
                'created_at' => '2024-02-20T09:15:00Z',
                'updated_at' => '2024-06-14T16:45:00Z',
                'status' => 'active',
                'roles' => ['user', 'admin']
            ]
        ],
        'meta' => [
            'current_page' => 1,
            'per_page' => 20,
            'total' => 2,
            'last_page' => 1
        ]
    ],
    
    'product_catalog' => [
        'categories' => [
            [
                'id' => 1,
                'name' => 'エレクトロニクス',
                'slug' => 'electronics',
                'description' => '最新の電子機器とガジェット',
                'products' => [
                    [
                        'id' => 101,
                        'name' => 'スマートフォン Pro',
                        'price' => 89800,
                        'currency' => 'JPY',
                        'in_stock' => true,
                        'specifications' => [
                            'screen_size' => '6.1インチ',
                            'storage' => '128GB',
                            'camera' => '12MP',
                            'battery' => '3000mAh'
                        ]
                    ],
                    [
                        'id' => 102,
                        'name' => 'ワイヤレスイヤホン',
                        'price' => 15800,
                        'currency' => 'JPY',
                        'in_stock' => true,
                        'specifications' => [
                            'battery_life' => '24時間',
                            'noise_cancelling' => true,
                            'water_resistance' => 'IPX4'
                        ]
                    ]
                ]
            ]
        ]
    ]
];

3. データベースシードファイル

データベース初期データの生成:

<?php
// database/seeders/UsersTableSeeder.php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UsersTableSeeder extends Seeder
{
    public function run()
    {
        $users = [
            [
                'name' => '管理者',
                'email' => '[email protected]',
                'email_verified_at' => now(),
                'password' => Hash::make('password'),
                'role' => 'admin',
                'profile' => [
                    'first_name' => '管理',
                    'last_name' => '者',
                    'phone' => '090-1234-5678',
                    'department' => 'システム管理部',
                    'bio' => 'システム全体の管理を担当しています。'
                ],
                'settings' => [
                    'theme' => 'dark',
                    'language' => 'ja',
                    'timezone' => 'Asia/Tokyo',
                    'notifications' => [
                        'email' => true,
                        'push' => true,
                        'sms' => false
                    ]
                ],
                'created_at' => now(),
                'updated_at' => now()
            ],
            [
                'name' => '田中太郎',
                'email' => '[email protected]',
                'email_verified_at' => now(),
                'password' => Hash::make('password'),
                'role' => 'user',
                'profile' => [
                    'first_name' => '太郎',
                    'last_name' => '田中',
                    'phone' => '090-2345-6789',
                    'department' => '開発部',
                    'bio' => 'フロントエンド開発を担当しています。'
                ],
                'settings' => [
                    'theme' => 'light',
                    'language' => 'ja',
                    'timezone' => 'Asia/Tokyo',
                    'notifications' => [
                        'email' => true,
                        'push' => false,
                        'sms' => false
                    ]
                ],
                'created_at' => now(),
                'updated_at' => now()
            ]
        ];

        foreach ($users as $userData) {
            DB::table('users')->insert([
                'name' => $userData['name'],
                'email' => $userData['email'],
                'email_verified_at' => $userData['email_verified_at'],
                'password' => $userData['password'],
                'role' => $userData['role'],
                'profile' => json_encode($userData['profile']),
                'settings' => json_encode($userData['settings']),
                'created_at' => $userData['created_at'],
                'updated_at' => $userData['updated_at']
            ]);
        }
    }
}

4. API レスポンステンプレート

API開発用のレスポンステンプレート:

<?php
// app/Http/Resources/ApiResponseTemplates.php
class ApiResponseTemplates
{
    public static function success($data = null, $message = '成功')
    {
        return [
            'status' => 'success',
            'message' => $message,
            'data' => $data,
            'timestamp' => now()->toISOString(),
            'request_id' => request()->header('X-Request-ID', uniqid())
        ];
    }

    public static function error($message = 'エラーが発生しました', $code = 500, $errors = null)
    {
        return [
            'status' => 'error',
            'message' => $message,
            'error_code' => $code,
            'errors' => $errors,
            'timestamp' => now()->toISOString(),
            'request_id' => request()->header('X-Request-ID', uniqid())
        ];
    }

    public static function pagination($data, $total, $page, $perPage)
    {
        return [
            'status' => 'success',
            'data' => $data,
            'pagination' => [
                'current_page' => $page,
                'per_page' => $perPage,
                'total' => $total,
                'last_page' => ceil($total / $perPage),
                'from' => ($page - 1) * $perPage + 1,
                'to' => min($page * $perPage, $total)
            ],
            'timestamp' => now()->toISOString()
        ];
    }

    public static function userProfile($user)
    {
        return [
            'id' => $user->id,
            'username' => $user->username,
            'email' => $user->email,
            'profile' => [
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'full_name' => $user->first_name . ' ' . $user->last_name,
                'avatar' => $user->avatar_url,
                'bio' => $user->bio,
                'location' => $user->location,
                'website' => $user->website
            ],
            'stats' => [
                'posts_count' => $user->posts()->count(),
                'followers_count' => $user->followers()->count(),
                'following_count' => $user->following()->count()
            ],
            'settings' => [
                'theme' => $user->settings['theme'] ?? 'light',
                'language' => $user->settings['language'] ?? 'ja',
                'privacy' => [
                    'profile_public' => $user->settings['privacy']['profile_public'] ?? true,
                    'email_public' => $user->settings['privacy']['email_public'] ?? false
                ]
            ],
            'timestamps' => [
                'created_at' => $user->created_at->toISOString(),
                'updated_at' => $user->updated_at->toISOString(),
                'last_login_at' => $user->last_login_at?->toISOString()
            ]
        ];
    }
}

🔧 技術詳解

データ型変換

JSONからPHPへのデータ型マッピング:

JSON型 PHP型 変換例
string string "text"'text'
number int/float 123123, 12.312.3
boolean boolean truetrue, falsefalse
null null nullnull
array array [1,2,3][1, 2, 3]
object array {"key":"value"}['key' => 'value']

特殊文字エスケープ

PHPコードでの特殊文字処理:

// 文字列エスケープの例
$examples = [
    'single_quote' => 'It\'s a test',           // シングルクォートエスケープ
    'double_quote' => "He said \"Hello\"",      // ダブルクォートエスケープ
    'backslash' => 'Path: C:\\Users\\Name',     // バックスラッシュエスケープ
    'newline' => "Line 1\nLine 2",              // 改行文字
    'tab' => "Column1\tColumn2",                // タブ文字
    'unicode' => 'こんにちは世界',               // Unicode文字(そのまま)
    'emoji' => '😀🎉🚀',                        // 絵文字(そのまま)
];

コード生成オプション

生成されるPHPコードのカスタマイズオプション:

// 短い配列構文(PHP 5.4+)
$data = [
    'key' => 'value'
];

// 従来の配列構文
$data = array(
    'key' => 'value'
);

// インデントスタイル
$data = [
    'level1' => [
        'level2' => [
            'level3' => 'value'
        ]
    ]
];

💡 使用のコツ

  • 構文確認:生成されたPHPコードの構文が正しいことを確認
  • エスケープ検証:特殊文字が適切にエスケープされているかチェック
  • パフォーマンス:大きなデータセットの場合はメモリ使用量に注意
  • セキュリティ:ユーザー入力データを含む場合は適切なサニタイズを実施

⚠️ 注意事項

  • JSON形式:入力JSONが有効な形式であることを確認
  • 文字エンコーディング:日本語文字が正しく処理されることを確認
  • メモリ制限:非常に大きなJSONファイルの処理時はメモリ制限に注意
  • セキュリティ:生成されたコードに機密情報が含まれていないか確認

🚀 使い方

  1. JSON入力:変換したいJSONデータを入力ボックスに貼り付け
  2. 変換実行:「変換」ボタンをクリックしてPHP配列コードを生成
  3. 結果確認:生成されたPHPコードが出力エリアに表示される
  4. コピー使用:「コピー」ボタンでPHPコードをクリップボードにコピー
  5. コード活用:PHPファイルに貼り付けて設定ファイルやデータとして使用

ヒント:このツールはクライアント側でローカル処理を行い、JSONデータをサーバーに送信しないため、機密性の高い設定情報も安全に変換できます。