如何使用PHP DOMDocument获取元素的序列化HTML?

时间:2010-09-27 15:15:21

标签: php dom domdocument

这是我的示例脚本:

$html = <<<HTML
<div class="main">
    <div class="text">
    Capture this text 1
    </div>
    <div class="date">
    May 2010
    </div>
</div>
<div class="main">
    <div class="text">
    Capture this text 2
    </div>
    <div class="date">
    June 2010
    </div>
</div>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);


$tags = $xpath->query('//div[@class="main"]');
foreach ($tags as $tag) {
    print_r($tag->nodeValue."\n");
}

这将出局:

Capture this text 1 May 2010
Capture this text 2 June 2010 

但我需要它输出:

<div class="text">
Capture this text 2
</div>
<div class="date">
June 2010
</div>

或者至少可以在我的foreach循环中做这样的事情:

$text = $tag->query('//div[@class="text"]')->nodeValue;
$date = $tag->query('//div[@class="date"]')->nodeValue;

2 个答案:

答案 0 :(得分:6)

好吧,nodeValue会给你节点的值。你想要的是通常所说的outerHTML

echo $dom->saveXml($tag);

将以符合X(HT)ML的方式输出您要查找的内容。


从PHP 5.3.6起,您还可以将节点传递给saveHtmlwhich wasnt possible previously:

echo $dom->saveHtml($tag);

后者将遵循HTML4语法。感谢Artefacto

答案 1 :(得分:-1)

试试这个

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$tags = $xpath->query('//div[@class="main"]');

foreach ($tags as $tag) {
    $innerHTML = '';

    $children = $tag->childNodes;
    foreach ($children as $child) {
        $tmp_doc = new DOMDocument();
        $tmp_doc->appendChild($tmp_doc->importNode($child,true));       
        $innerHTML .= $tmp_doc->saveHTML();
    }

    var_dump(trim($innerHTML));
}

-Pascal MARTIN