解析雅虎货币 http://finance.yahoo.com/connection/currency-converter-cache?date 的正确方法是什么?
What is the proper way to parse yahoo currency http://finance.yahoo.com/connection/currency-converter-cache?date?
作为我尝试并通过试用删除从 return 中获取 json 内容的代码如下
我用的方法。
$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);
代码 return 雅虎和 json 格式的给定批量
所以删除未知格式,即
"/**/YAHOO.Finance.CurrencyConverter.addConversionRates (" and ends with ");"
来自
$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){
}
我更喜欢使用 file_get_contents
来获取 html
和 preg_match_all
来清理 json
,即:
<?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"];
}
注意:
我已经测试了代码,它按预期工作。
作为我尝试并通过试用删除从 return 中获取 json 内容的代码如下 我用的方法。
$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);
代码 return 雅虎和 json 格式的给定批量
所以删除未知格式,即
"/**/YAHOO.Finance.CurrencyConverter.addConversionRates (" and ends with ");"
来自
$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){
}
我更喜欢使用 file_get_contents
来获取 html
和 preg_match_all
来清理 json
,即:
<?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"];
}
注意:
我已经测试了代码,它按预期工作。