Search code examples
phpxmlsimplexml

How to get array value from name instead index?


I have this following xml:

<result>
<rowset name="jumpClones" key="jumpCloneID" columns="jumpCloneID,typeID,locationID,cloneName"/>
<rowset name="jumpCloneImplants" key="jumpCloneID" columns="jumpCloneID,typeID,typeName"/>
<rowset name="implants" key="typeID" columns="typeID,typeName">
<row typeID="9899" typeName="Ocular Filter - Basic"/>
<row typeID="9941" typeName="Memory Augmentation - Basic"/>
<row typeID="9942" typeName="Neural Boost - Basic"/>
<row typeID="9943" typeName="Cybernetic Subprocessor - Basic"/>
<row typeID="9956" typeName="Social Adaptation Chip - Basic"/>
</rowset>
</result>

To get the value Ocular Filter - Basic, I'm using/through the rowset's index:

$array->result->rowset[2]->row[0]["typeName"];
                   //  ^

Now, the rowset[2] have: name="implants"

So, how to get the value with the array index attribute name (implants) instead pointing to the index 2?

I've tried:

$array->result->rowset["implants"]->row[0]["typeName"];

But it didn't work. What is the correct solution?


Solution

  • If you want to use implants as the basis of getting that node instead of choosing the index (as this will may vary), you could use an xpath query, if found point to it then access its children. Example:

    $implants = $array->xpath('//rowset[@name="implants"]');
    if(!empty($implants)) {
        echo $implants[0]->row[0]->attributes()->typeName;
    }
    

    Sample Output