【发布时间】:2011-01-14 11:42:50
【问题描述】:
所以我想知道是否有办法使用 PHP 获取特定 HTML 标记的信息。
假设我们有这段代码:
<ul>
<li>First List</li>
<li>Second List</li>
<li>Third List</li>
</ul>
如何搜索 HTML 并将第三个列表项的值放入变量中?或者有没有办法可以将整个无序列表拉到一个数组中?
【问题讨论】:
标签: php html arrays html-lists
所以我想知道是否有办法使用 PHP 获取特定 HTML 标记的信息。
假设我们有这段代码:
<ul>
<li>First List</li>
<li>Second List</li>
<li>Third List</li>
</ul>
如何搜索 HTML 并将第三个列表项的值放入变量中?或者有没有办法可以将整个无序列表拉到一个数组中?
【问题讨论】:
标签: php html arrays html-lists
尚未经过测试或编译,但一种方法是创建一个利用 PHP: DOMDocument 及其方法 getElementsByTagName 的函数,该函数返回一个
PHP: DOMNodeList 可以访问特定索引处的节点。
function grabAttributes($file, $tag, $index) {
$dom = new DOMDocument();
if (!@$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 (!@$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")
【讨论】:
li而不是"li",同时编辑代码,我想我想要的是$list->item($index)->nodeValue