问题
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 &
.
回答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