使用PHP从HTML标记中获取子节点列表


Getting the List of Child Nodes from within a HTML Tag using PHP

我目前正在使用PHP DOM从HTML中获取BODY标签。

$doc = new DOMDocument();
$doc->loadHTML($HTML);    
$body = preg_replace("/.*<body[^>]*>|<'/body>.*/si", "", $HTML);

上面的代码完全给了我一个给定html的body标签的html。

我可以得到与$body作为数组的HTML标签吗?

如果可能的话,我会使用DOM -它将使您的解决方案更可靠,使用起来更干净。

这应该会让你朝着正确的方向前进(对不起,我不是在为你写解决方案):

$html = file_get_contents("http://google.com");
$dom = new DOMdocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$elements = $xpath->query("//*");

foreach ($elements as $element) {
        echo "<h1>". $element->nodeName. "</h1>";
        $nodes = $element->childNodes;
        foreach ($nodes as $node) {
                echo "<h2>".$node->nodeName. "</h2>";
                echo $node->nodeValue. "'n";
        }
}