JSON to PHP Array Converter

Paste JSON and get a PHP array in short syntax, with the nesting kept. Every colon becomes => and every string gets single quotes with its own quotes escaped, so a real API response can go straight into a config file or a PHPUnit fixture.

INPUT JSON
PHP ARRAY OUTPUT

1 JSON to PHP Array example

Input JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[
    {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com",
        "roles": ["admin", "editor"],
        "active": true
    },
    {
        "id": 2,
        "name": "Jane Smith",
        "email": "jane@example.com",
        "roles": ["user"],
        "active": false
    }
]

PHP Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$users = [
    [
        'id' => 1,
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'roles' => [
            'admin',
            'editor'
        ],
        'active' => true
    ],
    [
        'id' => 2,
        'name' => 'Jane Smith',
        'email' => 'jane@example.com',
        'roles' => [
            'user'
        ],
        'active' => false
    ]
];

2 Where JSON to PHP Array output fits

Laravel and Symfony config

Laravel config files return PHP arrays, and Symfony PHP config passes arrays to each bundle. API documentation shows its examples as JSON, so paste the example here and copy the array across.

Test data

Convert a real response once and commit it as a fixture. The test then reads a static array instead of calling the API, so it runs the same way offline and in CI.

How to use the JSON to PHP Array tool

  1. Paste JSON into the left editor. Upload JSON loads a .json file, and From URL fetches an endpoint, as long as that endpoint allows cross-origin requests.
  2. The PHP array appears in the right panel as you type, with no convert button to press.
  3. If the JSON is invalid, the message next to the INPUT JSON label names the line that failed. Fix it and the output refreshes on its own.
  4. Click Beautify to reindent the JSON on the left, which helps when the input arrived minified.
  5. Click Copy to put the array on the clipboard, then paste it into a file that starts with <?php and assign or return it.

How to convert JSON to a PHP array in PHP, JavaScript and Python

PHP

<?php
$raw = '{"id":1,"name":"O\'Neil","tags":["a","b"],"active":true,"note":null}';

$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);

// var_export() prints valid PHP source for any array
$code = "<?php\n\nreturn " . var_export($data, true) . ";\n";
file_put_contents('config.php', $code);
echo $code;

var_export() emits the old array() syntax and writes NULL in capitals. The result looks dated, but it is valid on every PHP version.

JavaScript (Node.js)

const raw = '{"id":1,"name":"O\'Neil","tags":["a","b"],"active":true,"note":null}';

function toPhp(value, depth = 0) {
  const pad = "    ".repeat(depth + 1);
  const end = "    ".repeat(depth);
  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)) {
    return "[\n" + value.map((v) => pad + toPhp(v, depth + 1)).join(",\n") + "\n" + end + "]";
  }
  return "[\n" + Object.entries(value)
    .map(([k, v]) => pad + toPhp(k) + " => " + toPhp(v, depth + 1))
    .join(",\n") + "\n" + end + "]";
}

console.log("<?php\n\nreturn " + toPhp(JSON.parse(raw)) + ";");

Use this in a build script that turns fixtures.json into a PHP config file. It needs no packages.

Python

import json

raw = '{"id":1,"name":"O\'Neil","tags":["a","b"],"active":true,"note":null}'

def to_php(value, depth=0):
    pad, end = "    " * (depth + 1), "    " * depth
    if value is None:
        return "null"
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, (int, float)):
        return str(value)
    if isinstance(value, str):
        return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"
    if isinstance(value, list):
        items = [pad + to_php(v, depth + 1) for v in value]
    else:
        items = [pad + to_php(k) + " => " + to_php(v, depth + 1) for k, v in value.items()]
    return "[\n" + ",\n".join(items) + "\n" + end + "]"

print("<?php\n\nreturn " + to_php(json.loads(raw)) + ";")

Common errors and how to fix them

Parse error: syntax error, unexpected token "=>"
You pasted the array without a variable assignment or return. Write $data = [...]; or return [...]; and end the statement with a semicolon.
Parse error: unexpected single-quoted string, expecting "]"
A comma is missing between two elements, usually after a nested array. Check the line the error names and the one above it.
Array to string conversion
You echoed or concatenated an array value. Access a key such as $data['name'], or use print_r() or var_dump() when debugging.
Large integers lose precision
JSON numbers above PHP_INT_MAX (9223372036854775807) become floats. Store IDs and hashes that long as strings, or pass JSON_BIGINT_AS_STRING to json_decode().
Object keys with a numeric name become integers
PHP casts keys such as "1" to int 1. Iterating with foreach still works, but strict comparisons against the string "1" fail.

Good to know

The output is always an associative array, the same thing json_decode($json, true) gives you. Leave out that second argument and you get stdClass objects instead, accessed with ->. Objects are fine for reading, but arrays merge, serialize and go into array_* functions directly, so the tool produces arrays.

Do not rely on key order. PHP arrays keep insertion order, so keys come out in the order they appeared in the JSON. However, JSON itself makes no promise about key order, and the next parser in the chain may reshuffle them.

Specifications and references

This tool follows the specifications below. Read them when you need the exact normative wording, for example to settle an edge case between two implementations.

Guides and tutorials

Frequently Asked Questions

Does this support multidimensional arrays?

Yes. The converter walks the JSON recursively, so nested objects and arrays become nested PHP arrays at the same depth, however deep they go.

Is the output compatible with older PHP versions?

The output uses the short array syntax [], which works on PHP 5.4 and every later version, including PHP 8. If you need the legacy array() form, a find-and-replace on the brackets works as long as no string value contains a bracket.

Why not just call json_decode() in PHP?

Use json_decode() for data that arrives at runtime. This tool is for the cases where you want a static array in source code, such as a config file, a seeder, a translation file or a test fixture, with no decode step when the code runs.

How are JSON booleans and null converted?

true, false and null map to PHP's true, false and null. Numbers stay numbers. Strings go in single quotes with any single quote or backslash inside escaped, so O'Neil comes out as 'O\'Neil'.

Is my JSON uploaded anywhere?

No. The JSON is parsed with JSON.parse() in this tab and the array is built in JavaScript, so nothing is sent to a server. That makes it safe for API responses that contain private data.

Related

PHP array to JSON converts in the other direction. CSV to PHP array starts from a spreadsheet instead, and the JSON formatter shows where malformed input breaks.

More Data Converters

Browse all data converters

Copied to clipboard!