问题
<?php
libxml_use_internal_errors(true);
$html = '
<html>
<body>
<div>
Message <b>bold</b>, <s>strike</s>
</div>
<div>
<span class="how">
<a href="link" title="text">Link</a>, <b> BOLD </b>
</span>
</div>
</body>
</html>
';
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->strictErrorChecking = false;
$dom->recover = true;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$messages = $xpath->query("//div");
foreach($messages as $message)
{
echo $message->nodeValue;
}
This code returns "Message bold, strike Link, BOLD " without html tags...
I want to output the following code:
Message <b>bold</b>, <s>strike</s>
<span class="how">
<a href="link" title="text">Link</a>, <b> BOLD </b>
</span>
Can you help me?
回答1:
I can do it using SimpleXML really quickly (if it's okay for you to switch from DOMDocument and DOMXPath, probably you will go with my solution):
$html = '
<html>
<body>
<div>
Message <b>bold</b>, <s>strike</s>
</div>
<div>
<span class="how">
<a href="link" title="text">Link</a>, <b> BOLD </b>
</span>
</div>
</body>
</html>
';
$xml = simplexml_load_string($html);
$arr = $xml->xpath('//div/*');
foreach ($arr as $x) {
echo $x->asXML();
}
回答2:
$dom = new DOMDocument;
foreach($messages as $message)
{
echo $dom->saveHTML($message);
}
Use saveHTML()
来源:https://stackoverflow.com/questions/6177987/php-xpath-how-to-return-string-with-html-tags