PHP - xml to json conversion: "String could not be parsed as XML"

2.8k views Asked by At

I have a good xml file (huge, about 420K rows, but valid), and I'm simply trying to transform it in a json in this way:

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

when I run my php code it shows me 3 repeating warning:

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

Note that row 34 contains this instruction:

$xml = new SimpleXMLElement($xml_str);

and one fatal error:

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

I'll show you the first rows of my 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

There are 1 answers

0
Emile Pels On

Your XML is not valid. Replace the first line by

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