Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 577
Kirill Firsov Avatar asked Jan 26 '26 16:01

Kirill Firsov


1 Answers

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

Use saveHTML()

like image 92
Aminah Nuraini Avatar answered Jan 29 '26 05:01

Aminah Nuraini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!