Search code examples
phpjsonparsingyahoo-apiyahoo-finance

What is the proper way to parse yahoo currency http://finance.yahoo.com/connection/currency-converter-cache?date?


As the code i tried and by trial removal to get json content out of the return is below method i used.

$date= YYYYMMDD; 

//example '20140113'

$handle = fopen('http://finance.yahoo.com/connection/currency-converter-cache?date='.$date.'', 'r');

//sample code is http://finance.yahoo.com/connection/currency-converter-cache?date=20140208 paste the url in browser;

// use loop to get all until end of content 

   while (!feof($handle)) {
            $contents .= fread($handle, 8192);
        }
        fclose($handle);

the code return a given bulk in yahoo and json format

so remove the unknown format which is

   "/**/YAHOO.Finance.CurrencyConverter.addConversionRates (" and ends with ");"

by

  $contents = str_replace('/**/YAHOO.Finance.CurrencyConverter.addConversionRates(','',$contents);
        $contents = str_replace(');','',$contents);
        $obj = json_decode($contents,true);


then loop the content by 
foreach($obj['list']['resources'] as $key0 => $value0){

}

Solution

  • I prefer to use file_get_contents to get the html and preg_match_all to cleanup the json, i.e.:

    <?php
    $json = file_get_contents("http://finance.yahoo.com/connection/currency-converter-cache?date=20140113");
    preg_match_all('/\((.*)\);/si', $json, $json, PREG_PATTERN_ORDER);
    $json =  $json[1][0];
    $json = json_decode($json,true);
    
    foreach ($json["list"]["resources"] as $resource){
        echo $resource["resource"]["fields"]["date"];
        echo $resource["resource"]["fields"]["price"];
        echo $resource["resource"]["fields"]["symbol"];
        echo $resource["resource"]["fields"]["price"];
    }
    

    NOTE:

    I've tested the code and it works as intended.