Search code examples
phpxmlsimplexml

simplexml_load_file : iterate and separate node with attribute


I am completely unsure about the title for this, so sorry, here is my problem :

I am iterating through my xml and declaring variables out of it. It works fine, and looks like this :

$xml = simplexml_load_file('path/to/myxml.xml');
$bay0 = $xml->xpath("//Car[@park='0'  and contains(Group, '$filter')]");

foreach($bay0 as $vehicle) {
    $brand = $vehicle->Brand;
    $model = $vehicle->Model;
    $equips = $vehicle->Equipments
    [...]
 }

and so on.

In my xml, there are equipments for these cars. Equipments can have the attribute type="1" or type="2" like this :

 <Equipments>
      <Equipment type="1">automatic doors</Equipment>
      <Equipment type="2">full led headlights</Equipment>
  </Equipments>

I want to be able to separate equipments as two different variables in my foreach, depending of their type, but I did not find an answer to this, partly because I can't even properly formulate what I'm looking for.

Thanks for your help.

Edit :

Adding example of what I'm looking for :

  foreach($bay0 as $vehicle) {
    $brand = $vehicle->Brand;
    $model = $vehicle->Model;
    $equips1 = $vehicle->Equipments[type="1"];
    $equips2 = $vehicle->Equipments[type="2"];
 }

Solution

  • I think it could help you

    foreach($bay0 as $vehicle) {
        $brand = $vehicle->Brand;
        $model = $vehicle->Model;
    
        $equips=[];//start a array
        if($vehicle->Equipments[0]['type']=='1'){
            $equips[1] = $vehicle->Equipments;
        //$equips[1][] = $vehicle->Equipments; if many
        }
        elseif($vehicle->Equipments[0]['type']=='2'){
            $equips[2] = $vehicle->Equipments;
        //$equips[2][] = $vehicle->Equipments; if many
        }
    [...]
     }