Search code examples
phpxmllaravelapisimplexml

Trouble parsing XML with PHP (Laravel) - getting stuck at an "@" symbol in a property name


I have the following code:

$response = file_get_contents($xml_path);
   
$xml = simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA);
$xml2 = simplexml_load_string($xml->CompressedVehicles, 'SimpleXMLElement', LIBXML_NOCDATA);

foreach($xml2->RS->R->VS->V as $car) {
    dd($car);
}

That produces the following result:

SimpleXMLElement {#318 ▼
    +"@attributes": array:11 [▼
    "_0" => "1C6HJTAG8LL116179"
    "_1" => "2020"
    "_2" => "Jeep"
    "_3" => "Gladiator"
    "_4" => "Sport S"
    "_5" => "J9856"
    "_6" => "New"
    "_7" => "1"
    "_8" => "7/24/2019 12:00:00 AM"
    "_9" => "47615"
    "_10" => "0"
  ]
}

However, when I attempt to drill down into the $car variable, with:

dd($car->{'@attributes'});

or

dd($car->{'@attributes'}->{'_0'});

I get a null response.

I also have attempted alternate syntaxes, like you would use for a traditional array:

dd($car['@attributes']['_0']);

To no avail.

Any idea what I am missing here, or what I can do to access the information in this array?


Solution

  • Just in case anybody needs this in the future - I had to use the following syntax:

    dd($car->attributes()['_3']);
    

    That did the trick.