2012-04-23 47 views
0

我需要读取XML,我不找别的方式来阅读它只是这个,我只是harcoded的$电影,这和我得到这个错误信息:错误从谷歌新闻警告读取XML:的file_get_contents

Warning: file_get_contents(http://news.google.com.mx/news?hl=es&gl=mx&q=harry potter&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&um=1&ie=UTF-8&output=rss) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request 

我得到这个错误,这是我的代码,错误是在网址可以有人帮助,如何解决它?

$url = 
$data = file_get_contents('http://news.google.com.mx/news?hl=es&gl=mx&q='.$movie.'&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&um=1&ie=UTF-8&output=rss'); 

$xml = new SimpleXMLElement($data); 
$channel = array(); 
$channel['title'] = $xml->channel->title; 

foreach ($xml->channel->item as $item) 
{ 

    //echo $article['title'] = $item->title; 
    //echo $article['link'] = $item->link; 
    echo $article['pubDate'] = $item->pubDate; 
    echo $article['description'] = (string) trim($item->description); 

} 

回答

2

如果urlencode()的URL参数(即$movie),它应该正常工作。

例子:

$data = file_get_contents('http://news.google.com.mx/news?hl=es&gl=mx&q='. urlencode($movie) .'&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&um=1&ie=UTF-8&output=rss') 
+0

我尝试这样做:$数据=的file_get_contents(用urlencode('http://news.google.com.mx/news?hl=es&gl=mx&q='.$cine.'&bav=on.2, or.r_gc.r_pw.r_cp.r_qf,cf.osb&微米= 1&即= UTF-8&输出= RSS'))。并且我无法打开流: – bentham 2012-04-23 01:34:48

+0

中没有这样的文件或目录仅仅'$ movie'或查询字符串('?')后面传递的可能包含特殊字符或空格的任何其他参数。 – drew010 2012-04-23 01:36:22

+0

它的工作原理谢谢 – bentham 2012-04-23 01:40:10

2

你需要用的$movie中进行urlencode。我还添加了一个内容类型标题,以便您可以指定在该提要中使用的UTF-8编码,并为非英文字符正确渲染文本。

<?php 

header('Content-Type:text/html;charset=utf-8'); 

$movie = 'harry potter'; 
$url = 
$data = file_get_contents('http://news.google.com.mx/news?hl=es&gl=mx&q='.urlencode($movie).'&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&um=1&ie=UTF-8&output=rss'); 

$xml = new SimpleXMLElement($data); 
$channel = array(); 
$channel['title'] = $xml->channel->title; 

foreach ($xml->channel->item as $item) 
{ 
    //echo $article['title'] = $item->title; 
    //echo $article['link'] = $item->link; 
    echo $article['pubDate'] = $item->pubDate; 
    echo $article['description'] = (string) trim($item->description); 
} 

?> 
+0

谢谢你的回答 – bentham 2012-04-23 01:46:25