Search code examples
phpxmllaravellaravel-8php-8

Laravel or PHP how to acces to XML file and read value and properties


I have this XML file with this structure and I want to read it from Laravel, for this I use SimpleXMLElement.

I can access the "id" and "colour" attributes but I don't know how to access the value in this case the example would be "porsche or ferrari"

XML File

<?xml version="1.0"?>
<cars>
    <car id="0001" colour="blue">porsche</car>
    <car id="0002" colour="red">ferrari</car>
</cars>

PHP Code

$xmlString = file_get_contents($filename);

$xml = new \SimpleXMLElement($xmlString);

foreach ($xml->children() as $child) {
    dd($child);
}

Output Result

SimpleXMLElement {#562
  +"@attributes": array:2 [
    "id" => "0001"
    "colour" => "blue"
  ]
  +"0": "porsche"
}

I can access to ID or colour with $child['id'] or $child['colour'], but I don't know how to access the value of ferrari or porsche


Solution

  • You can access properties and attributes like so:

    $xmlString = file_get_contents($filename);
    
    $xml = new \SimpleXMLElement($xmlString);
    
    foreach ($xml->children() as $car) {
        echo $car; // porsche
        echo $car['id']; // 0001
        echo $car['colour']; // blue
    
        $carName = (string) $car;
        $carId = $car['id'];
        $carColour = $car['colour'];
    }