包含"&"的字符串出错在XML.我怎样才能解决这个问题


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

我使用以下代码将我的数据从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>

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

按如下方法尝试utf8_encode函数

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

:

) ENGINE=MyISAM DEFAULT COLLATION utf8_general_ci CHARSET=utf8;

希望它对你有用。

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

正确的代码是:

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