包含“&”的字符串出错在XML中。我怎样才能解决这个问题?

时间:2011-07-24 17:14:59

标签: php xml simplexml

我使用以下代码将我的数据从XML导入到mySQL。 有没有办法编码&在使用PHP加载它而不是从文件中手动更改它之前?

这是错误

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

这是我的xml

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

2 个答案:

答案 0 :(得分:4)

尝试utf8_encode函数,如下所示

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

用于mySql表使用:

) ENGINE=MyISAM DEFAULT COLLATION utf8_general_ci CHARSET=utf8;

希望它适合你。

更新:我错过了$ data是一个数组...

正确的代码是:

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

答案 1 :(得分:4)

您没有从MySQL服务器收到错误。您的错误来自simplexml_load_file(),因为您正在阅读的源XML文件包含错误。特别是,文字&必须编码为&amp;

相关问题