PHP - xml到json转换:" String无法解析为XML"

时间:2017-12-20 11:48:07

标签: php json xml-parsing xmlconvert

我有一个很好的xml文件(巨大的,大约420K行,但是有效),我只是试图以这种方式在json中转换它:

$xml_str = file_get_contents('jobs.xml');
$xml = new SimpleXMLElement($xml_str);
$json = json_encode($xml);

当我运行我的PHP代码时,它向我显示了3个重复警告:

Warning: SimpleXMLElement::__construct(): Entity: line 1: parser error : error parsing attribute name in /retrieve.php on line 34
Warning: SimpleXMLElement::__construct(): <xml version="1.0" encoding="UTF-8" ?> in /retrieve.php on line 34
Warning: SimpleXMLElement::__construct(): ^ in /retrieve.php on line 34

请注意,第34行包含此指令:

$xml = new SimpleXMLElement($xml_str);

和一个致命错误:

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /retrieve.php:34 Stack trace: #0 /retrieve.php(34): SimpleXMLElement->__construct('<xml version="1...') #1 {main} thrown in /retrieve.php on line 34

我将向您展示我的xml的第一行:

<xml version="1.0" encoding="UTF-8" ?>
<jobs>

   <job>
      <category>Transport / logistics / warehouse</category>
      <description>Bla bla bla </description>
      <post_date>2017-12-01</post_date>
      <salary>60000</salary>
   </job>

....
</jobs>

1 个答案:

答案 0 :(得分:3)

您的XML无效。用

替换第一行
<?xml version="1.0" encoding="UTF-8" ?>