I am trying to save data from my xml file into the mysql database using codeigniter & php. But I couldn’t find a way to escape special xml characters to save my data from the xml file to my table, cache_table.
Code:
$xml_source = str_replace(array("&", "&"), array("&", "&"),file_get_contents('XML/customer.xml'));
$xml = simplexml_load_string($xml_source);
foreach($xml as $row )
{
$attr = $row->attributes();
$results[] = array('CustomerAccountNumber' => $this->db->escape_str($attr->CustomerAccountNumber),'Desciption' => $this->db->escape_str($attr->Desciption) ):
$this->db->insert_batch('cache_cust',$results);
But I am getting this error:
Error:
simplexml_load_string(): Entity: line 37: parser error : Unescaped ‘<‘ not allowed in attributes values.
customer.xml
<?xml version="1.0" standalone="yes"?>
<Rows>
<Row CustomerAccountNumber="12" Name="Arj" Desciption="PJ psm" />
<Row CustomerAccountNumber="1" Name="Aj" Desciption="*/Artic" />
<Row CustomerAccountNumber="2" Name="smla" Desciption="& light" />
<Row CustomerAccountNumber="3" Name="alik" Desciption="*/Artic" />
<Row CustomerAccountNumber="4" Name="wqla" Desciption="" />
<Row CustomerAccountNumber="5" Name="walij" Desciption="16-17" />
<Row CustomerAccountNumber="6" Name="li" Desciption="sales@llil.com" />
</Rows>
How can I avoid this error and avoid special xml characters so that my code save all the records from the xml file into the database?
You will want to review the htmlentities to encode and html_entity_decode to restore them back. Using the htmlentities will allow you to not have to worry about replacing each of the special characters like the ampersand individually and it will replace the arrows as well. I believe the escape_str will take care of the quotes for you.
The documentation found in the links below should assist you with any unanswered questions.
http://php.net/manual/en/function.htmlentities.php
http://www.php.net/manual/en/function.html-entity-decode.php