get data from JSON with php

半腔热情 提交于 2019-12-13 09:48:15

问题


I am trying to get data from a JSON page: http://www.oref.org.il/WarningMessages/alerts.json

I am getting errors.

How do I get the "data" array from the JSON?

Here is an example of what I am doing:

$homepage = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result   = json_decode($result);
$result   = utf8_encode($result); 
print_r($result);

回答1:


$result = file_get_contents ("http://www.oref.org.il/WarningMessages/alerts.json");

 $result = iconv('UTF-16', 'UTF-8', $result);
 $json = json_decode($result);
 echo $json->id;
 echo $json->title;



回答2:


json_encode returns an object (or an associative array if you give the second argument true). To get the data array, you need to use a property accessor:

$homepage = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result = json_decode($homepage);
$data = $result->data;
print_r($data);

If you need to encode the $data array in UTF8, use:

$data = array_map('utf8_encode', $result->data);

To get the title, use:

$title = utf8_encode($data->title);



回答3:


You could do this:

$result = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result = json_decode($result);
print_r($result->data);



回答4:


First of all, you are first json_decode($result); but $result has not been declared before this line.

Secondly, the logically order of your code is totally wrong:

$result = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result = utf8_encode($result); // encode the data before decoding json

$result = json_decode($result, true); // specify true to get an associated array

print_r($result);



回答5:


Test.json:

{
    "John":{
        "name":"Json"
    },
    "James":{   
        "status":"Active",
        "age":56,
        "count":10,
        "progress":0.0029857,
        "bad":0
    }
}

json.php:

$result= file_get_contents("test.json");
$get_data = json_decode($result, true);

echo $get_data['John']['name'].'<br/>';
echo $get_data['James']['age'];


来源:https://stackoverflow.com/questions/24725519/get-data-from-json-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!