0
我試圖從一堆網頁中拉出鏈接並在表格中報告它們。我有這個函數,get_links($ pageId),它應該得到頁面的內容,並拉出每個錨標籤的值和href屬性。PHP DOM:nodeValue作爲對象讀取而不是字符串
function get_links($pageId) {
$page_contents = file_get_contents('http://www.mysite.com/?p='.$pageId);
$html = new DOMDocument();
@$html->loadHTML($page_contents);
$anchors = $html->getElementsByTagName('a');
$link_array = array();
foreach($anchors as $anchor) {
if (!empty($anchor->nodeValue)) {
$text = $anchor->nodeValue;
$link = $anchor->getAttribute('href');
$link_array[$text] = $link;
}
}
return $link_array;
}
當我在其中一個頁面上運行此函數時,它不返回任何內容。例如,如果我打電話:
$page_links = get_links('someId');
foreach($page_links as $text->$link) {
//my print functions
};
我得到「致命錯誤:無法訪問空屬性」的foreach行。
在foreach($ anchors)循環中回顯$ text和$ link會正常工作。所以在循環後回顯$ link_array的值。但回顯鍵沒有。如果我把這個測試中循環後右:
foreach($link_array as $text->$link) {echo $text;}
我得到這個錯誤:「開捕致命錯誤:類stdClass的客體不能轉換爲字符串。」
爲什麼它會在循環過程中打印好,但是當我把它放在一個數組中時會被當作對象返回?
+1'$ text => $ link' NOT'$ text - > $ link'。閱讀錯誤消息。 – Xeoncross
Duh。謝謝。這是一段時間,因爲我用PHP編碼...語法錯誤總是讓我! – tkm256