Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON string contents into PHP Array

Tags:

json

php

I am trying to parse a string in JSON, but not sure how to go about this. This is an example of the string I am trying to parse into a PHP array.

$json = '{"id":1,"name":"foo","email":"[email protected]"}';  

Is there some library that can take the id, name, and email and put it into an array?

like image 801
tony2 Avatar asked Nov 28 '12 07:11

tony2


People also ask

How can I get JSON encoded data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

Can we use JSON parse in PHP?

Parsing JSON with PHPPHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.

How can you decode JSON string?

You just have to use json_decode() function to convert JSON objects to the appropriate PHP data type. Example: By default the json_decode() function returns an object. You can optionally specify a second parameter that accepts a boolean value. When it is set as “true”, JSON objects are decoded into associative arrays.


3 Answers

You can use json_decode()

$json = '{"id":1,"name":"foo","email":"[email protected]"}';  

$object = json_decode($json);

Output: 
    {#775 ▼
      +"id": 1
      +"name": "foo"
      +"email": "[email protected]"
    }

How to use: $object->id //1

$array = json_decode($json, true /*[bool $assoc = false]*/);

Output:
    array:3 [▼
      "id" => 1
      "name" => "foo"
      "email" => "[email protected]"
    ]

How to use: $array['id'] //1

like image 185
Ilya Degtyarenko Avatar answered Oct 09 '22 09:10

Ilya Degtyarenko


Try json_decode:

$array = json_decode('{"id":1,"name":"foo","email":"[email protected]"}', true);
//$array['id'] == 1
//$array['name'] == "foo"
//$array['email'] == "[email protected]"
like image 34
Musa Avatar answered Oct 09 '22 10:10

Musa


It can be done with json_decode(), be sure to set the second argument to true because you want an array rather than an object.

$array = json_decode($json, true); // decode json

Outputs:

Array
(
    [id] => 1
    [name] => foo
    [email] => [email protected]
)
like image 23
MrCode Avatar answered Oct 09 '22 09:10

MrCode