2012-11-26 36 views
-1

我正在嘗試使用codeigniter & php將我的xml文件中的數據保存到mysql數據庫中。但我找不到一種方法來轉義特殊的xml字符,以將我的數據從xml文件保存到我的表cache_table。在Codeigniter/php中轉義xml字符

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); 

但我收到此錯誤:

錯誤:

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="[email protected]" /> 
</Rows> 

我怎樣才能避免這種錯誤,避免特殊xml字符如此我的代碼保存了xml文件中的所有記錄到數據庫中?

+0

可以粘貼您的XML數據? – GBD

+0

@GBD我在question.thanks中添加了xml數據。 –

+1

在XML中具有特殊含義的字符在SQL中不可能有特殊含義。你爲什麼認爲你需要逃避任何事情? –

回答

0

錯誤說明了一切:

Unescaped '<' not allowed in attributes values. 

所以你的XML是無效的。它是如何首先被破壞的?大概是因爲這個:

$xml_source = str_replace(array("&amp;", "&"), array("&", "&amp;"),file_get_contents('XML/customer.xml')); 
0

的ActiveRecord將在他們即'"逃避與引號字符的字符串照顧。所以你不需要明確地使用諸如mysql_real_escape_string()之類的東西。其他XML字符將會很好,並且不需要轉義<>

此外,您(或其他人)在XML屬性中拼寫「Desciption」錯誤。