无法从定义id的xpath中检索值

时间:2012-05-16 19:28:31

标签: php yql

我试图从yql生成的xml中获取id“yfs_a00_xauusd = x”的数据..

我试过了..但结果是

向: 是http://finance.yahoo.com/q?s=XAGUSD%3DX&ql=1 613 600 27426 28.3600我只想抓住 28.3600

<?php
session_start();
$yql_base_url = "http://query.yahooapis.com/v1/public/yql";  
$xpath='//*[@id="yfs_g00_xagusd=x"]';
$url = 'http://finance.yahoo.com/q?s=XAGUSD%3DX&ql=1';
$yql_query = "select * from html where url=$url and xpath = $xpath;";  
$yql_query_url = $yql_base_url . "?q=" . urlencode($yql_query);
$yql_query_url .= "&env=http://datatables.org/alltables.env";
$yql_query_url .= "&format=json";
$session = curl_init($yql_query_url);  
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);      
$json = curl_exec($session);
$phpObj =  json_decode($json);  

if(!is_null($phpObj->query->results->span)){  
    foreach($phpObj->query->results->span as $result){  
        $_SESSION['price'] = $result;
  }  
}  
?>


<div> Ask:<?php echo $_SESSION['span'];?> </div>

雅虎生成的XML是....

<query yahoo:count="1" yahoo:created="2012-05-16T19:00:25Z" yahoo:lang="en-US">
  <diagnostics>
    <publiclyCallable>true</publiclyCallable>
    <url execution-start-time="1" execution-stop-time="601" execution-time="600" proxy="DEFAULT">http://finance.yahoo.com/q?s=XAGUSD%3DX&ql=1</url>
    <user-time>613</user-time>
    <service-time>600</service-time>
    <build-version>27426</build-version>
  </diagnostics>
  <results><span id="yfs_g00_xagusd=x">28.3600</span></results>
</query>

我非常感谢你的帮助..提前致谢。

1 个答案:

答案 0 :(得分:2)

您的查询已损坏,应引用这些值。

$yql_query = "select * from html where url='$url' and xpath='$xpath';";

或者更好的是,通过查询参数提供这些值。

$yql_query = "select * from html where url=@url and xpath=@xpath;";
$params = array(
     'q'      => $yql_query,
     'url'    => $url,
     'xpath'  => $xpath,
     'env'    => 'http://datatables.org/alltables.env',
     'format' => 'json',
);
$yql_query_url = $yql_base_url . '?' . http_build_query($params);

一旦你有YQL返回你真正想要的结果,你可以找到你想要的价格。

$phpObj->query->results->span->content

请参阅a running example