-1

I am using an API that give me a XML response (with Curl) I need to parse the response to get a specific value

I follow the php documentation

<?php
$string = <<<XML
<?xml version='1.0'?> 
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);

print_r($xml);
?>

But in my case, the response of the curl is something like this without <<<XML XML; tag and simplexml_load_string give me empty object

`
<?xml version='1.0'?>
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>`;

In fact, how I can surround my response with this tag ?

Jonathan COHEN
  • 125
  • 1
  • 2
  • 8
  • 1
    You may find your answer on this page: [enter link description here](https://stackoverflow.com/questions/6578832/how-to-convert-xml-into-array-in-php) – Hamed Aug 23 '22 at 21:01

1 Answers1

1

You can transform it into associative array by encoding the XML object as JSON and then decoding it back into array like so:

$string = <<<XML
<?xml version='1.0'?> 
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);

$xml = json_encode($xml);
$xml = json_decode($xml, true);