简单的XML加载文件不起作用
为什么这不起作用:
$url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20xpath%3D%22%2F%2Fmeta%22%20and%20url%3D%22http://www.cnn.com%22&format=xml&diagnostics=false";
$xml = (simplexml_load_file($url))
我收到多个错误,告诉我HTTP请求失败。最终,我希望将此文件中的结果放入数组中,例如
Description=cnn.com发布最新突发新闻等。
关键词=CNN、CNN新闻、CNN.com、CNN TV等
但这个初始阶段不起作用。有什么需要帮忙的吗?
编辑 更多信息:
错误:
warning: simplexml_load_file(http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20xpath%3D%22//meta%22%20and%20url%3D%22http://www.cnn.com%22&format=xml&diagnostics=false) [function.simplexml-load-file]: failed to open stream: HTTP request failed! # warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20xpath%3D%22//meta%22%20and%20url%3D%22http://www.cnn.com%22&format=xml&diagnostics=false"
- 从我的phpinfo(): 允许打开 上的_url_fopen
- PHP版本5.2.11
- 认为它是有效的(http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20xpath%3D%22//meta%22%20and%20url%3D%22http://www.cnn.com%22&;format=xml&;diagnostics=false)
解决方案
(注意:一旦找到真实答案…,则可能无用)
当您解决XML问题时(继续研究它!)要知道,您还可以将YQL响应作为JSON返回。这里有一个简单的例子:
$url = "http://query.yahooapis.com/v1/public/yql?q=select+%2A+"
. "from+html+where+xpath%3D%22%2F%2Fmeta%5B%40name%3D%27"
. "Keywords%27+or+%40name%3D%27Description%27%5D%22+and+"
. "url%3D%22http%3A%2F%2Fwww.cnn.com%22&format=json&diagnostics=false";
// Grab YQL response and parse JSON
$json = file_get_contents($url);
$result = json_decode($json, TRUE);
// Loop over meta results looking for what we want
$items = $result['query']['results']['meta'];
$metas = array();
foreach ($items as $item) {
$metas[$item['name']] = $item['content'];
}
print_r($metas);
给出如下数组(截断屏幕的文本):
Array
(
[Description] => CNN.com delivers the latest breaking news and …
[Keywords] => CNN, CNN news, CNN.com, CNN TV, news, news online …
)
请注意,为了使PHP更简单,YQL查询(try it in the console)与您的略有不同。
相关文章