ali raha
ali raha

Reputation: 221

wrong output with php dom

I have a simple rich utf-8 text like this:

$content = '<p> a simple <a href="http://unicode.com"> UTF-8</a> text.
                  <img src ="http://unicode.com/pic.jpeg" /></p>'

So I want to change src value with php dom:

$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
$imgs = $doc->getElementsByTagName('img');
 $newsrc = 'http://unicode.com/pic.png';
foreach ($imgs as $img) 
{
     $img->setAttribute('src', $newsrc);
}
$content = $doc->saveHTML();
echo $content;

I except this output result:

<p> a simple <a href="http://unicode.com"> UTF-8</a> text.
                  <img src ="http://unicode.com/pic.png" /> </p>

But I get something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html><body>6;&#1585<p><a href="http://unicode.com">&#1608;&#1740; &#1662;&#1575;&#1585;&#1587;: </a>
&#1662;&#1575;&#1740;&#1711;&#1575;&#1607;
<img src="http://unicode.com/pic.png" /></p></body></html>

Now I do not want any extra tags like DOCTYPE,html,body,... And I want normal char not like &#1711; and like that.

how can I solve it?

Upvotes: 0

Views: 215

Answers (1)

user142162
user142162

Reputation:

This is possible with PHP 5.4+. Simply pass the LIBXML_HTML_NODEFDTD and LIBXML_HTML_NOIMPLIED flags to DOMDocument::loadHTML:

$doc->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

If PHP 5.4+ is not an option for you, see the DOMDocument::saveHTML comments for alternative solutions.

Upvotes: 1

Related Questions