0

我需要读取一个 xml,我没有找到另一种读取它的方法,我只是对 $movie 和这个进行了编码,然后我收到了这个错误消息:

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 中有人可以帮忙,如何解决?

$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);

}
4

2 回答 2

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')
于 2012-04-23T01:34:10.277 回答
2

您需要将$moviein 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);
}

?>
于 2012-04-23T01:38:51.833 回答