Home  >  Q&A  >  body text

Access and read values ​​and properties in XML files in Laravel or PHP

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

I can access the "id" and "color" attributes but I don't know how to access the value, in this case the example is "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 the ID or color using $child['id'] or $child['colour'] but I don't know how to access the value of Ferrari or Porsche

P粉012875927P粉012875927283 days ago526

reply all(1)I'll reply

  • P粉976737101

    P粉9767371012023-12-16 11:00:38

    You can access attributes and properties like this:

    $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'];
    }
    

    reply
    0
  • Cancelreply