[英]unable to decode json via php from url
I am trying to read json vi php but unable to decode 我正在尝试阅读json vi php但无法解码
<?php
$json_url = "http://chartapi.finance.yahoo.com/instrument/1.0/AAPL/chartdata;type=quote;range=5d/json";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
If you visit your target URL you will notice the JSON value is wrapped in a callback method which you could trim as by something like 如果您访问目标URL,您会注意到JSON值包装在回调方法中,您可以使用类似以下方法进行修整
$json = str_replace('finance_charts_json_callback(', '', substr($pageContent, 0, strlen($pageContent) - 1));
Here is how it looks all put together: 这是所有看起来的样子:
<?php
$json_url = "http://chartapi.finance.yahoo.com/instrument/1.0/AAPL/chartdata;type=quote;range=5d/json"; $pageContent = file_get_contents($json_url);
$json = str_replace('finance_charts_json_callback(', '', substr($pageContent, 0, strlen($pageContent) - 1));
$data = json_decode($json, TRUE);
echo "<pre>"; print_r($data); echo "</pre>";
One thing you can do is work with it in JavaScript: 您可以做的一件事就是在JavaScript中使用它:
<script>
function finance_charts_json_callback(json){
console.log(json.meta);
}
</script>
<?php
$json_url = "http://chartapi.finance.yahoo.com/instrument/1.0/AAPL/chartdata;type=quote;range=5d/json";
$data = file_get_contents($json_url);
echo "<script>";
print_r($data);
echo "</script>";
?>
Other thing is try to remove the 'function' part: 另一件事是尝试删除“功能”部分:
<?php
$json_url = "http://chartapi.finance.yahoo.com/instrument/1.0/AAPL/chartdata;type=quote;range=5d/json";
$json = file_get_contents($json_url);
$json = substr($json, 30);
$json = substr($json, 0, strlen($json)-2);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
The response from this service is not a valid JSON object its JSONP, you should look for a service that provides output as JSON. 此服务的响应不是其JSONP的有效JSON对象,因此您应该寻找一个将输出作为JSON提供的服务。
In case they don't provide a service like that you can manipulate the data before decoding it using this workaround 如果他们没有提供这样的服务,您可以使用此替代方法在解码数据之前对其进行操作
$data = str_replace('finance_charts_json_callback( ', '', $data);
$data = str_replace(' )', '', $data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.