A PHP json_encode array conversion example

If you need to see a simple PHP example that converts an array of data to a JSON string using the json_encode function, I hope this little script is helpful:

<?php

#
# do some stuff here ...
#

# send a json reply back to the sencha client
header('Content-type: text/html');
echo json_encode(array(
    "success" => true,
    "msg" => $message,
    "id" => $id
));

?>

I omitted a lot from that script, but as you can see at the end of the script, I use the PHP json_encode method to convert a PHP array to JSON.

The output from that script varies depending on the values of $message and $id=, but some sample output looks like this JSON string:

{"success":true,"msg":"","id":100}

A PHP to JSON multidimensional array example

A real-world scenario is to return an array of arrays from PHP as a JSON string, using json_encode. Here’s how that works. This code:

<?php

header('Content-type: text/html');
echo json_encode(
    array(
        array('symbol' => 'AAPL', 'price' => '525.00'),
        array('symbol' => 'GOOG', 'price' => '600.00'),
        array('symbol' => 'TSLA', 'price' => '220.00')
    )
);

?>

yields this JSON output:

[{"symbol":"AAPL","price":"525.00"},{"symbol":"GOOG","price":"600.00"},{"symbol":"TSLA","price":"220.00"}]

As you can see, in the PHP code I have an array of arrays that map a stock symbol to its price, and convert that to JSON by calling json_encode, and the code results in the output shown.

 

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.