Unterminated entity reference in PHP

↘锁芯ラ 提交于 2019-12-02 21:42:17
Joel Davey

This correctly encodes the & < > and "" ''

$parent->addChild($name, htmlspecialchars($value));

SimpleXMLElement is actually a system resource which behaves like an object. Which makes working with loops tricky. So when trying to add new child elements instead of this:

$product->addchild('element', $value);

do this:

$product->element = $value;

or you can use htmlspecialchars(), to escape html characters.

Note:

mysql_* is deprecated as of and removed as of . So instead use mysqli_* or PDO.
Why shouldn't I use mysql_* functions in PHP?

Kavi Siegel

My solution to this is specifically creating a text node, which makes sure absolutely everything is escaped properly:

$cell = $dom->createElement('td');
$cell->appendChild($dom->createTextNode($value));
swapnesh

Try by changing -

$product->addchild('image_url','$row[imag_url]');

To

$product->addchild('image_url',"$row[\"imag_url\"]");

OR

$product->addchild('image_url',$row['imag_url']);

EDIT wrap quotes too round image_url, courtesy Barrmar

Eolia

The correct form is:

$product->addchild('image_url',htmlspecialchars($row['imag_url']));
Peter

Sorry for reviving an old question, but there is another solution to this.. Assuming the following code causes the "unterminated entity reference" error:

$xml->addChild($key,$value); 

@Joel-Davey's solution works very well:

$xml->addChild($key,htmlspecialchars($value)); 

But you can also do the following if, for some reason, you don't want to use the above htmlspecialchars function (basically, you split the one step into two steps):

$xml->addChild($key); 
$xml->$key=$value; 

i have no idea which one will execute faster; i doubt it'd make much of a difference, but, this works, and i thought it should be mentioned

PS: i know it works because i'm using it on a personal project

If you use the new created node you can set the value by accessing {0} property. This should escape any special characters.

$childNode = $parent->addChild($name);
$childNode{0} = $value;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!