The JSON to PHP converter transforms JSON data into PHP formats. Generates either PHP serialize format for storage/transmission or PHP array syntax for code generation and configuration files.
case 'json-to-php': { const val = parseJsonLoose(input); if (action === 'to-array') return { output: phpArraySyntax(val as PhpValue) }; return { output: phpSerialize(val as PhpValue) };}
PHP Serialize (lib/tools/php-tools.ts:99-127):
export function phpSerialize(value: PhpValue): string { if (value === null) return 'N;'; if (typeof value === 'boolean') return `b:${value ? 1 : 0};`; if (typeof value === 'number') { return Number.isInteger(value) ? `i:${value};` : `d:${value};`; } if (typeof value === 'string') { const byteLen = new TextEncoder().encode(value).length; return `s:${byteLen}:"${value}";`; } if (Array.isArray(value)) { const items = value.map((v, i) => `i:${i};${phpSerialize(v)}`).join(''); return `a:${value.length}:{${items}}`; } if (typeof value === 'object') { const entries = Object.entries(value); const items = entries .map(([k, v]) => { const key = /^\d+$/.test(k) ? `i:${parseInt(k)};` : `s:${new TextEncoder().encode(k).length}:"${k}";`; return key + phpSerialize(v); }) .join(''); return `a:${entries.length}:{${items}}`; } return 'N;';}
export function phpArraySyntax(value: PhpValue, indent = 0): string { const pad = ' '.repeat(indent); const inner = ' '.repeat(indent + 1); if (value === null) return 'null'; if (typeof value === 'boolean') return value ? 'true' : 'false'; if (typeof value === 'number') return String(value); if (typeof value === 'string') { return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}' `; } if (Array.isArray(value)) { if (value.length === 0) return '[]'; const items = value .map((v) => `${inner}${phpArraySyntax(v, indent + 1)}`) .join(',\n'); return `[\n${items},\n${pad}]`; } if (typeof value === 'object') { const entries = Object.entries(value); if (entries.length === 0) return '[]'; const items = entries .map(([k, v]) => { const key = /^\d+$/.test(k) ? k : `'${k}'`; return `${inner}${key} => ${phpArraySyntax(v, indent + 1)}`; }) .join(',\n'); return `[\n${items},\n${pad}]`; } return 'null';}
The JSON to PHP converter uses UTF-8 byte length for string serialization, ensuring correct handling of multibyte characters (emoji, Unicode, etc.).
For PHP config files, use the “To Array” action to generate clean, readable PHP array syntax. Wrap the output with <?php\n\nreturn and ; to create a valid PHP file.
Serialized PHP data should only be unserialized in trusted contexts
The serializer generates modern short array syntax ([]), not compatible with PHP versions before 5.4
Very deeply nested JSON structures may cause stack overflow during serialization