开发者

PHP XPath. How to return string with html tags?

<?php
    libxml_use_internal_errors(true);
    $html = '
<html>
<body>
    <div>
        Message <b>bold</b>, <s>strike</s>
    </div>
    <div>
        &开发者_如何转开发lt;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?


$dom = new DOMDocument;
foreach($messages as $message)
{
    echo $dom->saveHTML($message); 
}

Use saveHTML()


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();
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜