Access and read values ​​and properties in XML files in Laravel or PHP
P粉012875927
P粉012875927 2023-12-15 11:54:24
0
1
606

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粉012875927
P粉012875927

reply all(1)
P粉976737101

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'];
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template