1
所以我想知道是否有辦法使用PHP獲取特定HTML標籤的信息。PHP抓取HTML標籤行/層次
比方說,我們有這樣的代碼:
<ul>
<li>First List</li>
<li>Second List</li>
<li>Third List</li>
</ul>
我怎麼能搜索HTML並拉動第三列表項的值到一個變量?或者有沒有辦法可以將整個無序列表拖入數組中?
所以我想知道是否有辦法使用PHP獲取特定HTML標籤的信息。PHP抓取HTML標籤行/層次
比方說,我們有這樣的代碼:
<ul>
<li>First List</li>
<li>Second List</li>
<li>Third List</li>
</ul>
我怎麼能搜索HTML並拉動第三列表項的值到一個變量?或者有沒有辦法可以將整個無序列表拖入數組中?
尚未經過測試或編譯,而是一種方法是創建使用PHP: DOMDocument的功能和它的方法getElementsByTagName
它返回一個 PHP: DOMNodeList,你可以在一個特定的索引來訪問節點。
function grabAttributes($file, $tag, $index) {
$dom = new DOMDocument();
if ([email protected]$dom->load($file)) {
echo $file . " doesn't exist!\n";
return;
}
$list = $dom->getElementsByTagName($tag); // returns DOMNodeList of given tag
$newElement = $list->item($index)->nodeValue; // initialize variable
return $newElement;
}
如果調用grabAttributes("myfile.html", "li", 2)
的變量將被設置爲"Third List"
或者你可以做一個函數把給定標籤的所有屬性到一個數組。
function putAttributes($file, $tag) {
$dom = new DOMDocument();
if ([email protected]$dom->load($file)) {
echo $file . " doesn't exist!\n";
return;
}
$list = $dom->getElementsByTagName($tag); // returns DOMNodeList of given tag
$myArray = array(); // array to contain values.
foreach ($list as $tag) { // loop through node list and add to an array.
$myArray[] = $tag->nodeValue;
}
return $myArray;
}
如果你打電話putAttributes("myfile.html", "li")
它將返回array("First List", "Second List", "Third List")
它沒有工作。使用grabAttributes我得到這個錯誤: 可捕捉的致命錯誤:類DOMElement的對象無法轉換爲字符串 – NessDan 2010-02-08 18:36:42
嘗試使用'li'而不是''li'',同時編輯代碼,我想我想要的是'$ list-> item($ index) - > nodeValue' – 2010-02-08 18:37:16
你先生,是即時winrar。感謝修復編輯。 – NessDan 2010-02-08 18:46:28