2017-04-12 73 views
0

我正面臨使用PHP從Wired讀取RSS源的奇怪問題。我想要在我的網站上顯示Feed。我正在使用下面的代碼來獲取提要。任何人都可以讓我知道我到底在做錯什麼。無法使用PHP讀取來自Wired的RSS源

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

excecuting上面的代碼後,我收到以下錯誤

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! 

我還檢查了有線供稿網址中的「Feed驗證(https://www.feedvalidator.org/)和有效性及其稱其有效RSS提要...

任何幫助非常感謝,謝謝!

+0

我相信這是XML嘗試通過使用simplexml_load_file功能 –

+0

加載它看看http://stackoverflow.com/questions/10617142/loading-rss-feed-into-php –

+0

如果你想處理RSS,這是一個不錯的項目:https://github.com/simplepie/simplepie/ – Sebastian

回答

0

我試圖用我的方式該代碼使用curlsimplexml

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

哇......上面的代碼適用於我,但是在我的代碼中失敗的地方在哪裏? –

+0

它也適用於'DOMDocument'風味,它只是喜歡通過curl來使用。 'file_get_contents'只是混淆了返回值 – Ghost

+0

@Ghost是的,用於'https'' file_get_contents'發送gzip加密內容。 – Gaurav

0

謝謝@Gaurav ..和我與DOM文檔版本