简体   繁体   中英

Usage of json_encode and json_decode

I am new to PHP. I am using json_encode to convert an array into json data, and decode it using json_decode in another file. However, I am getting json error as syntax error.

My code is as follows:

File 1:

$result = get_data_array();

exit(json_encode($result));

File 2:

$result = file_get_contents("http://localhost/file1.php");
$data = json_decode($result,true);

$data->name // name is the array key

However, I am getting an error as:

Trying to get property of non-object.

You passed true to the second parameter of json_decode so it will return an array.

Use this:

$result = file_get_contents("http://localhost/file1.php"); 
$data = json_decode($result,true);
echo $data['name'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM