简体   繁体   中英

PHP save HTML on DOMDocument

$html = <<<HTML
<div class="hey">test</div>
<div id="no">bla</div>
<div class="hey"><b>sa</b> hey<div id="l">b</div></div>  
HTML;

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$q = '//div[@class="hey"]';
$arr = $xpath->query($q);
foreach($arr as $el) {
    echo $el->nodeValue;
}  

I have this code above, but it doesn't save the html inside the class "hey". How can I save the HTML inside the divs?

Try $e1->textContent instead of $e1->nodeValue

textContent

This attribute returns the text content of this node and its descendants.

nodeValue

The value of this node, depending on its type

you may use saveXML or saveHTML with the optional contextNode-argument(set it to $el) to get the string. This string will also contain div.hey , remove it via RegExp.

Please Note: saveHTML supports the optional contextNode since version 5.3.6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM