使用 PHP 解析 JSON 并显示内容


Parsing JSON with PHP and displaying contents

我有此代码问题

这是我与其他项目一起使用的PHP...

$gas = file_get_contents('http://api.mygasfeed.com/stations/loadbygeo/47.9494949/120.23423432/reg|mid|pre|diesel/'. $api . '.json?callback=?');

$json_output = json_decode(utf8_decode($gas));
$location= $json_output->geoLocation->city_id;

这是 JSON 结果

?({"status":{"error":"NO","code":200,"description":"none","message":"Request    ok"},"geoLocation":{"city_id":"13123","city_long":"Hulunber","region_short":"Nei Mongol","region_long":"Nei Mongol","country_long":"China","country_id":"49","region_id":"6010"},"stations":[]})

此代码返回空白结果。

您需要

删除?()。 参见WP:JSONP。

人们可以使用substr(),或者更好的是正则表达式来断言并仅删除所需的垃圾:

$json = preg_replace("/ ^[?'w(]+ | [)]+'s*$ /x", "", $jsonp);

将删除任意callbackFnNames(,还会删除您奇怪的?(伪函数调用。