开发者

How can I get an element's serialised HTML with PHP's DOMDocument?

开发者 https://www.devze.com 2023-01-17 14:38 出处:网络
This is my example script: $html = <<<HTML <div class=\"main\"> <div class=\"text\">

This is my example script:

$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");
}

This will out put:开发者_Python百科

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

But I need it output:

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

Or atleast be able to do something like this in my foreach loop:

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


Well, nodeValue will give you the node's value. You want what's commonly called outerHTML

echo $dom->saveXml($tag);

will output what you are looking for in an X(HT)ML compliant way.


As of PHP 5.3.6 you can also pass a node to saveHtml, which wasnt possible previously:

echo $dom->saveHtml($tag);

The latter will obey HTML4 syntax. Thanks to Artefacto for that.


try this

$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

0

精彩评论

暂无评论...
验证码 换一张
取 消