Command Palette

Search for a command to run...

JSON to PHP Array: Turn a JSON Blob Into Ready-to-Paste PHP

JSON to PHP Array: Turn a JSON Blob Into Ready-to-Paste PHP

T
Toolz Team
|Aug 31, 2026|15 Мин. читать

Часть коллекции Инструменты для данных

I have written more PHP than any other language, first as a WordPress plugin developer and later building SaaS backends in Laravel, and there is one small chore that comes up constantly and that I got tired of doing by hand. You have a JSON blob, a config sample, an API response, a fixture, and you need it as a PHP array in your source code. Not decoded at runtime, actually written into the file as a literal. Retyping the brackets and arrows by hand is slow, and it is exactly the kind of mechanical translation a tool should do. So I built one into toolz.dev, and this is the guide to it.

TL;DR: The Toolz JSON to PHP array converter parses a JSON document and serialises it as a PHP array literal you can paste straight into a file. JSON objects become associative arrays with =>, JSON arrays become indexed arrays, and scalars map to their PHP equivalents. Choose short [] or classic array() syntax, set the indentation, and optionally wrap the result in a $variable = [...]; assignment. It runs entirely client-side: no upload, no signup, works offline.

What is a JSON to PHP array converter?

A JSON to PHP array converter turns a JSON document into the equivalent PHP array literal. A JSON object becomes an associative array written with the => operator, a JSON array becomes an indexed array, and the scalar types map directly: a JSON string becomes a single-quoted PHP string, true and false stay the same, null stays null, and numbers keep their value. Nesting is preserved to any depth, so a deeply structured JSON object comes out as a deeply structured PHP array with the same shape.

The reason this is useful is that JSON and PHP arrays describe the same thing, a tree of keyed and ordered values, with different punctuation. JSON uses colons and braces; PHP uses => and brackets. Translating between them is pure mechanics, and mechanics are error-prone when done by hand, especially with nested structures where a single misplaced bracket breaks the file. The converter does the translation deterministically and hands you back valid PHP.

It is worth being clear about what this is not. It is not json_decode. PHP reads JSON at runtime perfectly well, and when your data arrives as a string, decoding it is the right move. This tool is for the other case, when you want the array to live in the source code itself.

Why not just use json_decode?

This is the first question every PHP developer asks, and it is the right one. json_decode($string, true) parses a JSON string into a PHP array, and the PHP manual documents it as the standard way to consume JSON. If your JSON is data that arrives at runtime, from an HTTP request, a queue, a file you read, then json_decode is exactly what you should use, and no code generator belongs anywhere near it.

The converter is for a different situation: when the JSON is not runtime data but something you want committed to code. A few concrete cases from my own work. A default configuration array that ships with a plugin and should be readable and editable in the source. A lookup table, say a map of country codes to names, that you paste once and never fetch. A test fixture that needs to be a literal so the test is self-contained and does not depend on reading a file. A seed for a database migration. An example in documentation that has to be copy-pasteable PHP rather than JSON.

In all of those, decoding a JSON string on every request would be wasteful and would hide the data behind a string literal, where your editor cannot fold it, your linter cannot check it, and a reviewer cannot read it as PHP. Writing the array into the source solves that. The converter is the fastest way to get from a JSON sample to that literal.

Here is the decision in one table.

Situation Use Why
JSON arrives at runtime as data json_decode($json, true) Parsing is the job; keep it dynamic
JSON is config, fixtures, seeds, examples JSON to PHP array converter Commit a readable literal to source
You need JSON back out of a PHP value json_encode($array) The reverse direction
You have a PHP serialize() string unserialize tool That is a different format entirely

What is the difference between short [] and array() syntax?

They produce identical arrays; only the brackets differ. The short syntax uses [ and ] and has been available since PHP 5.4, which is now ancient history, so for any modern codebase short syntax is the default and the one I reach for. The classic array() form works in every version of PHP ever released, which is the only reason to still choose it: you are targeting a runtime older than PHP 5.4, or a codebase whose style guide mandates the long form.

The tool lets you switch between them without re-pasting your JSON, so if you are contributing to an older project you can match its house style in one click. My advice for anything new is short syntax, and PSR-12, the modern PHP coding style, is written around it.

How are strings and special characters handled?

This is the part that bites people who write their own quick converter, so it is worth explaining. The tool emits strings as PHP single-quoted literals. Inside single quotes, PHP treats almost every character literally; the only two that are special are the backslash and the single quote itself. So the converter escapes exactly those two, a backslash becomes two backslashes and a single quote gets a preceding backslash, and it leaves everything else alone.

That has a pleasant consequence. A newline inside a JSON string comes through as a real newline inside the single-quoted PHP string, which is valid and preserves the character exactly. You do not get the mangling you would if the tool naively tried to apply double-quote escape sequences. A JSON string like O'Brien becomes 'O\'Brien', and a Windows path like C:\Users becomes 'C:\\Users', both of which are correct PHP. If you have ever debugged a config file where an apostrophe in a value silently broke the syntax, you will appreciate that this is handled for you.

How do I use the converter?

The flow is four steps. Paste a JSON object or array into the input box; if you want to see the shape of the output first, load the sample. Pick the array syntax, short [] or array(). Set the indentation to 2 spaces, 4 spaces, or a tab, to match your project, and optionally type a variable name to wrap the output as $config = [...]; with a trailing semicolon, ready to drop into a file. Then click Convert and copy the result.

If the JSON is invalid, the tool reports the parser's own error message rather than failing silently, so a stray trailing comma or an unquoted key is quick to find. And because everything runs in your browser, you can paste a real API response or a private config without it leaving your machine, which matters when the values are not something you would send to a random server. That client-side model is the same one behind the rest of the site, described in the data privacy online tools guide.

How does this fit with the other JSON tools?

The JSON to PHP array converter is one member of a small family of JSON transformers on the site, and they share the same parsing core. When you want to tidy the JSON first, the JSON formatter will indent and validate it. When you need the same data as a TypeScript interface instead of PHP, the JSON to TypeScript converter infers the types. When the target is a spreadsheet or a database load, the JSON to CSV converter flattens it into rows, and the JSON to YAML converter handles config formats that prefer YAML.

For PHP developers specifically, the neighbour worth knowing is the unserialize tool, which handles PHP's own serialize() format. That is a different beast from JSON, a PHP-specific wire format you find in session data and some WordPress option values, and the two tools cover the two ways structured data commonly shows up in a PHP project. If you work across the stack, the web developer toolkit roundup shows how these pieces slot together, and the developer productivity tools guide covers the wider set.

A worked example from a WordPress and Laravel workflow

Let me make this concrete with the two places I hit it most. In a WordPress plugin, you often ship a default settings array that seeds the options table on activation. During development that structure frequently starts life as a JSON sample, maybe exported from a settings UI or sketched out while designing the schema. Rather than hand-translate it, I paste the JSON into the converter, pick short syntax and 4-space indentation to match the plugin's style, type defaults as the variable name, and get back $defaults = [ ... ]; that drops straight into a get_default_settings() function. The keys stay readable, a reviewer can see the shape in the diff, and there is no runtime decode on every page load.

The Laravel side is similar but shows up in config and seeders. A config file returns a big associative array, and I regularly have a JSON version of some third-party mapping, a currency table, a set of feature flags, a list of plans, that needs to become that array. The converter turns the JSON into the literal, I wrap it in the return [ ... ]; the config file expects, and the value is now first-class PHP that the framework caches with config:cache instead of being parsed from a string. For database seeders the same trick works: paste the JSON of your sample rows, get an array, and feed it to insert().

The reason I lean on a converter rather than json_decode(file_get_contents(...)) in these spots is not laziness, it is that committing the literal makes the data part of the code review, part of the static analysis, and part of the version history in a form a human reads. A JSON file sitting next to the code is invisible to a PHP linter; an array in the source is not. When the data is a fixed part of the application rather than input to it, that visibility is worth the one-time conversion.

There is also a documentation angle that I underestimated until I started writing more guides. When you want to show a PHP example in a README or a knowledge base, a JSON blob is not copy-pasteable PHP, and readers who grab it hit a syntax error. Running it through the converter first means the example in your docs is real, runnable PHP that a reader can drop into a file and see work, which is a small thing that quietly raises the quality of the documentation.

What are the limits worth knowing about?

A few honest edges. The biggest is numeric precision, and it is a property of JSON parsing in general rather than this tool specifically. The converter parses your JSON with the browser's JSON parser, which represents numbers as double-precision floats. Integers beyond roughly 2 to the 53rd power, sixteen-ish digits, lose precision at parse time, before the tool ever sees them. If you are converting JSON with very large integer IDs, treat those as strings in the JSON to keep them exact. Every JSON.parse-based converter shares this limit; a tool that claimed otherwise would be lying.

Second, PHP array key coercion. PHP quietly converts a string key that looks like an integer into an actual integer key. The converter writes object keys as quoted strings, which is explicit and correct, but be aware that PHP itself may treat '0' and 0 as the same key at runtime. This only matters for objects whose keys are numeric strings, which is rare, and the behaviour is PHP's, not the tool's.

Third, empty containers. An empty JSON object {} and an empty JSON array [] both become [] in PHP, because a PHP array cannot distinguish the two. That is a genuine ambiguity in the mapping, not a shortcut, and there is no PHP construct that preserves the difference.

Finally, the output is a value, not a statement, unless you supply a variable name. Without one you get a bare literal, which is what you want when pasting into an existing expression; with one you get a complete assignment ending in a semicolon. The variable name is validated, so an invalid identifier is rejected with a clear message rather than producing broken PHP.

Frequently asked questions

What is a JSON to PHP array converter? A JSON to PHP array converter transforms a JSON document into the equivalent PHP array literal. JSON objects become associative arrays with the => operator, JSON arrays become indexed arrays, and the scalar types map to their PHP counterparts so you can paste the result directly into a script.

How do I convert JSON to a PHP array? Paste your JSON into the input box, choose short [] or array() syntax and an indentation style, then click Convert. The tool builds a PHP array literal you can copy, optionally wrapped in a variable assignment if you enter a variable name.

What is the difference between short [] and array() syntax? They produce identical arrays; only the brackets differ. Short syntax uses [] and has been available since PHP 5.4, while array() is the older form that works in every PHP version. Choose array() only if you must support a runtime older than PHP 5.4.

Does this replace json_decode in PHP? No. json_decode($json, true) parses a JSON string into an array at runtime, which is right when the JSON arrives as data. This tool writes the array into your source code instead, which suits config, fixtures, seed data, and examples that should live in the file rather than be decoded on every request.

How are JSON objects and arrays mapped? A JSON object becomes a PHP associative array where each key is a single-quoted string followed by => and its value. A JSON array becomes an indexed PHP array with the elements in order. Nesting is preserved to any depth exactly as in the source.

How are strings and special characters handled? Strings are emitted as PHP single-quoted literals, so only a backslash and a single quote are escaped with a preceding backslash. Every other character, including a real newline, is kept verbatim, which matches how PHP treats single-quoted strings.

Is my JSON uploaded anywhere? No. The conversion happens entirely in your browser using JavaScript on your device. Your JSON is never uploaded, logged, or stored, and the tool continues to work with the network disconnected once the page has loaded.

Is the JSON to PHP array converter free? Yes. It is completely free with no signup, no watermark, and no usage cap. Convert as many JSON documents to PHP arrays as you need for personal or commercial projects.

Comments

0 comments

0/2000 characters

No comments yet. Be the first to share your thoughts!