Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

auroralabs's avatar

Convert XML response to JSON

Hi,

I am trying to get a response from an old asp API that returns XML data and convert it into JSON and although I am getting a response it is not formatting and outputting JSON. Can anyone suggest a solution to this issue or what I am doing wrong?

    public function getSupercontrolDetails()
    {
        $client = new Client();
        $response = $client->request('GET', 'https://api.supercontrol.co.uk/xml/property_xml.asp?id=94298&siteID=14978', [
            'headers' => [
                'Accept'     => 'text/xml'
            ]
        ]);
        if ($response->getStatusCode() == 200) {

            $response = json_encode(simplexml_load_string($response->getBody()->getContents()));
            
        }
        dd($response);
    }

0 likes
6 replies
bobbybouwmann's avatar

What exactly is not working for you?

I think you have to first try parts out. Is the content of the response in proper XML? What does simplexml_load_string return for you?

wingly's avatar

Don't you need to json_decode it too ??

auroralabs's avatar
public function getSupercontrolDetails()
{
    $client = new Client();
    $response = $client->request('GET', 'https://api.supercontrol.co.uk/xml/property_xml.asp?id=94298&siteID=14978', [
        'headers' => [
            'Accept'     => 'text/xml'
        ]
    ]);
    if ($response->getStatusCode() == 200) {

        $response = json_encode(simplexml_load_string($response->getBody()->getContents()));
        $response = json_decode($response);
    }
    dd($response);
}

With json decode it returns similar to the following with most of the data missing and replaces with # for example the propertyname #459 instead of "Fairway House, St. Andrews"

{#452 ▼
  +"error": {#454}
  +"property": {#453 ▼
    +"propertyname": {#459}
    +"propertycode": "94298"

Without json decode the data comes back but not formatted and is missing all the content fields that include the fo example propertyname":{}

"{"error":{},"property":{"propertyname":{},"propertycode":"94298","flipkeyID":{}
bobbybouwmann's avatar

Well, that is because simplexml_load_string returns all kind of PHP objects. You might need an extra layer to convert those objects to the correct structure before you json_encode it.

auroralabs's avatar

yes, I saw a function somewhere on Laracast somewhere but cannot seem to find the discussion feed as i think some stripping of the response is needed first.

Please or to participate in this conversation.