PHP XPath. How to return string with html tags?

假如想象 提交于 2020-01-24 15:59:45

问题


<?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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!