Error on strings that contains “&” in XML. How can I fix this?

99封情书 提交于 2021-01-28 01:49:23

问题


I am using the following code to import my data from XML to mySQL. Is there any way to encode & before loading it using PHP instead of manually change it from the file?

this is the error

Warning: simplexml_load_file() [function.simplexml-load-file]: products.xml:4: parser error : xmlParseEntityRef: no name in ... on line 5

Warning: simplexml_load_file() [function.simplexml-load-file]: <description> DAYLIGHT & LED / SMD Tech</description> in ... on line 5

Warning: simplexml_load_file() [function.simplexml-load-file]: ^ in ... on line 5

Warning: Invalid argument supplied for foreach() in ... on line 8

this is a sample element of my xml

<?xml version="1.0" encoding="UTF-8"?>
<description>Νέας γενιάς & τεχνολογίας DAYLIGHT LED / SMD Tech</description>

回答1:


You are not getting an error from the MySQL Server. Your error comes from simplexml_load_file() because the source XML file you are reading contains errors. In particular, a literal & must be encoded as &amp;.




回答2:


try the function utf8_encode as follows

$col = '`'. implode('`,`',$columns) .'`';
$val = '"'. implode('","',utf8_encode($data)).'"';
$query = "INSERT INTO products ($col) VALUES ($val)";
mysql_query($query);

for your mySql table use:

) ENGINE=MyISAM DEFAULT COLLATION utf8_general_ci CHARSET=utf8;

hope it work for you.

UPDATE: I've missed that $data was an array...

the right code is:

$data[] = mysql_real_escape_string((string)utf8_encode($child));


来源:https://stackoverflow.com/questions/6808351/error-on-strings-that-contains-in-xml-how-can-i-fix-this

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!