Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unterminated entity reference in PHP

Here is my code:

<?php
// 27/01/2016 Edit:
$result = mysql_query("A Long mysql query");
$rss = new SimpleXMLElement('<rss version="2.0" />');
$products = $rss->addChild('products');
///
while($row = mysql_fetch_array($result)){
$product = $products->addChild('category');
$product->addChild('product_id',"$row[product_id]");
$product->addChild('cat_id',"$row[cat_id]");
$product->addChild('cat_name',"$row[cat_name]");
$product->addchild('product_code',"$row[product_code]");
$product->addchild('product_name',"$row[product_name]");
$product->addChild('description','$row[description]');
$product->addchild('rating',"$row[rating]");
$product->addchild('image_url','$row[imag_url]');
$product->addchild('price',"$row[price]");
$product->addchild('discount',"$row[discount]");
$product->addchild('stock_status',"$row[stock_status]");
$product->addchild('stock_quantity',"$row[stock_quantity]");
$product->addchild('weight',"$row[weight]");
$product->addchild('length',"$row[length]");
$product->addchild('width',"$row[width]");
$product->addchild('height',"$row[height]");
$product->addchild('colour',"$row[colour]");
$product->addchild('size',"$row[size]");
$product->addchild('material',"$row[material]");
$product->addchild('pattern',"$row[pattern]");
};

Header('Content-type: text/xml');
print($rss->asXML());
?>

and here is the error:

Warning: SimpleXMLElement::addChild() [simplexmlelement.addchild]: unterminated entity reference _Coke.jpg in C:\wamp\www\rabwah\core.php on line 40

The error is in the line with '$row[imag_url]'.

like image 954
mega6382 Avatar asked Jun 10 '13 15:06

mega6382


3 Answers

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

$parent->addChild($name, htmlspecialchars($value));
like image 113
Joel Davey Avatar answered Oct 11 '22 04:10

Joel Davey


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 php-5.5 and removed as of php-7. So instead use mysqli_* or PDO.
Why shouldn't I use mysql_* functions in PHP?

like image 46
mega6382 Avatar answered Oct 11 '22 05:10

mega6382


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));
like image 9
Kavi Siegel Avatar answered Oct 11 '22 05:10

Kavi Siegel