1

I am trying to read json vi php but unable to decode

<?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>";

?>
  • 2
    You also can find some general solution for decoding JSONP on http://stackoverflow.com/questions/5081557/extract-jsonp-resultset-in-php – Ali Dec 27 '16 at 18:58

3 Answers3

2

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

$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>";
Ali
  • 2,993
  • 3
  • 19
  • 42
  • thank ali,it worked, can you help me little more, how can fetch last value of $data 'series' 'close' after every 5 min, not asking to code it for me, just an idea. – Devinderjeet Singh Dec 27 '16 at 19:37
  • Let me have a look at the data and get back to you – Ali Dec 27 '16 at 20:02
  • So something like `$lastOfSeries = end($data['series']);` will store the last item from the series into the $lastOfSeries variable – Ali Dec 27 '16 at 20:10
1

One thing you can do is work with it in 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>";

?>
sheldonled
  • 118
  • 7
1

The response from this service is not a valid JSON object its JSONP, you should look for a service that provides output as 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);