Problem with encoding when use insertBefore in DOMDcocument with WordPress response

30 Views Asked by At

I have a php variable with html, I want to make some changes with DomDocument, like insert a new tag with:

$dom->getElementsByTagName('div')->item(0)->insertBefore($new_element, $first_child);

everything work fine but when are present special characters like à,è,ò the response is a character like �

I tried with the classic directive like:

<?xml version="1.0" encoding="UTF-8"?> before html content

or DOMDocument('1.0', 'UTF-8')

or utf8_decode()

this resolve the problem in general of all html content, but when I made the changes with

$dom->getElementsByTagName('div')->item(0)->insertBefore($new_element, $first_child);

it returns these characters like for this new hmtl element added

here my code:

$html content is a return of get_the_content() in wordpress

$nomiClassi = array('namea', 'nameb');

$dom = new DOMDocument();
        
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach ($nomiClassi as $nomeClasse) {
    $xpath = new DOMXPath($dom);
    $nodes = $xpath->query("//*[@class='$nomeClasse']");
    
    foreach ($nodes as $node) {
        $node->parentNode->removeChild($node);
    }
}

$new_element = $dom->createElement('h2', get_the_title()  );
$first_child = $dom->getElementsByTagName('div')->item(0)->firstChild;
$dom->getElementsByTagName('div')->item(0)->insertBefore($new_element, $first_child);
$newHtml = utf8_decode($dom->saveHTML($dom->documentElement) );

some advice ?

0

There are 0 best solutions below