当我尝试导入xml文件时,它返回一个错误:
xmlParseCharRef:无效的xmlChar值
4"
因为xml$amp;
中的<STOCKGROUP >NAME="ABC & Glass" RESERVEDNAME="">
这是我用来读取xml文件数据的代码
function add_product_type()
{
print_r($_FILES);
if (isset($_FILES['product_type_file']) && ($_FILES['product_type_file']['error'] == UPLOAD_ERR_OK)) {
$use_errors = libxml_use_internal_errors(true);
$response = simplexml_load_file($_FILES['product_type_file']['tmp_name']);
print_r($response);
foreach($response->BODY->IMPORTDATA as $key => $value) {
foreach($value->REQUESTDATA->TALLYMESSAGE as $key => $values) {
if (strstr("&", $values->STOCKGROUP->attributes())) {
$name = str_replace("&", "&", $values->STOCKGROUP->attributes());
}
else {
$name = $values->STOCKGROUP->attributes();
}
echo $name . ",";
}
}
if ($response == false) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
}
}
XML没有HTML实体的概念。作为一个黑客,你可以与decode the entities first
$html = html_entity_decode($file_contents, ENT_QUOTES, "utf-8");
然后尝试使用XML解析器解析$html
。只是希望它足够宽容,因为HTML仍然不是有效的XML。
好消息是你可以删除if (strstr("&",
hack,因为这是由html_entity_decode()
处理的。
您的XML示例与获取错误并且处理正常的数据不同,但这并不意味着您的代码是正确的。在你的主循环中,你使用$values->STOCKGROUP->attributes()
作为名称,但是如果你使用了这个值的print_r()
,你会看到它带有一个所有属性值的列表,你的代码将它们全部合并为一个字符串。
SimpleXMLElement Object
(
[@attributes] => Array
(
[NAME] => Alluminium Section & Glass
[RESERVEDNAME] =>
)
)
如果你只想要<STOCKGROUP NAME="Alluminium Section & Glass" RESERVEDNAME="">
的NAME属性,那么使用STOCKGROUP['NAME']
。而且不仅仅是替换&
,使用html_entity_decode()
转换名称中的任何字符。
foreach($response->BODY->IMPORTDATA as $key => $value) {
foreach($value->REQUESTDATA->TALLYMESSAGE as $key => $values) {
$name = html_entity_decode((string)$values->STOCKGROUP['NAME']);
echo $name . ",";
}
}
此代码与您提供的示例输出...
Alluminium Section & Glass,
更新:检查正在加载的文件...
$data = file_get_contents($_FILES['product_type_file']['tmp_name']);
echo $data;
$use_errors = libxml_use_internal_errors(true);
$response = simplexml_load_string($data);
echo $response->asXML();