【问题标题】:PHP Grab HTML Tag Rows/HierarchyPHP 抓取 HTML 标签行/层次结构
【发布时间】: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


    【解决方案1】:

    尚未经过测试或编译,但一种方法是创建一个利用 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")

    【讨论】:

    • 它没有用。使用grabAttributes我得到了这个错误:可捕获的致命错误:类DOMElement的对象无法在中转换为字符串
    • 尝试li而不是"li",同时编辑代码,我想我想要的是$list-&gt;item($index)-&gt;nodeValue
    猜你喜欢
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多