我正面临一个奇怪的问题,即使用PHP从Wired阅读RSS feed。我想在我的网站上显示Feed。我使用以下代码来获取Feed。任何人都可以让我知道我在哪里做错了。
try {
$rss = new DOMDocument();
$rss->load('https://www.wired.com/category/reviews/feed/');
if ($rss->validate()) {
echo "This document is valid!\n";
}else{
echo "This document is not valid!\n";
}
}catch (Exception $e) {
return array('error'=>'Error raised in reading the feed','exception'=>$e);
}
$feeds = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
);
array_push($feeds, $item);
}
在执行上述代码后,我收到以下错误
Warning: DOMDocument::load(): Start tag expected, '<' not found in https://www.wired.com/category/reviews/feed/, line: 1 in D:\xampp\htdocs\my_functions\index.php on line 4
Warning: DOMDocument::validate(): no DTD found! in D:\xampp\htdocs\my_functions\index.php on line 5
This document is not valid!
我还检查了&#34; Feed验证器(https://www.feedvalidator.org/)中有线Feed网址的有效性,并说它是一个有效的RSS Feed ......
任何帮助非常感谢。谢谢!
答案 0 :(得分:0)
我使用curl
和simplexml
$handle = curl_init('https://www.wired.com/category/reviews/feed/');
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($handle, CURLOPT_ENCODING, 'identity');
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
curl_close($handle);
$xml = simplexml_load_string($response, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$data = json_decode($json, true);
// print_r($data);
$feeds = array();
if(isset($data['channel']['item'])) {
foreach($data['channel']['item'] as $item) {
$feeds[] = array(
'title' => $item['title'],
'desc' => $item['description'],
'link' => $item['link'],
);
}
}
print_r($feeds);
答案 1 :(得分:0)
谢谢@Gaurav ..和我的版本与Domdocument
define('RSS_FEED_URL', 'https://www.wired.com/category/reviews/feed/');
try {
// fetch the rss feeds from wired!
$handle = curl_init(RSS_FEED_URL);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($handle, CURLOPT_ENCODING, 'identity');
$response = curl_exec($handle);
curl_close($handle);
$rss = new DOMDocument();
$rss->loadXML($response);
}catch (Exception $e) {
echo "Failed to fetch RSS Feed properly for Blogs!!";
return array();
}
foreach ($rss->getElementsByTagName('item') as $node) {
$feeds[] = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
// 'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
}