2012-04-23 51 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