Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

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

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

This will out put:

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...