1

我这样做:

$dom = new DOMDocument;
$dom->loadHTMLFile("test.html");
//$books = $dom->getElementsByTagName('body');

$i = 0;
while (is_object($finance = $dom->getElementsByTagName("body")->item($i))) {
    foreach ($finance->childNodes as $nodename) {
        if ($nodename->childNodes) {
            foreach ($nodename->childNodes as $subNodes) {
                if ($subNodes->childNodes) {
                    foreach ($subNodes->childNodes as $potha){
                        echo $potha->nodeName . " - " . $potha->nodeValue . "<br>";
                    }
                } else {
                    echo $subNodes->nodeName . " - " . $subNodes->nodeValue . "<br>";
                }
            }
        } else {
            echo $nodename->nodeName . " - " . $nodename->nodeValue . "<br>";
        }
    }
    $i++;
}

但是我怎样才能让它递归,所以每次有 subChild 时,它应该循环遍历每个孩子,子孩子和子孩子等等....否则回显节点的名称和值。

另外,我如何获得每个节点相对于 body 或 html 的位置,因此每个段之间存在差异。

4

1 回答 1

3

像这样的东西应该适合你:

function treatNode($node)
{
    if ($node->hasChildNodes()) {
        foreach ($node->childNodes as $child){
            treatNode($child);
        }
    } else {
        echo $node->nodeName . " - " . $node->nodeValue . "<br>";
    }
}

$dom = new DOMDocument;
$dom->loadHTMLFile("test.html");
//$books = $dom->getElementsByTagName('body');

$i = 0;
while (is_object($finance = $dom->getElementsByTagName("body")->item($i))) {
    treatNode($finance);
    $i++;
}
于 2012-12-12T09:32:03.207 回答