Search code examples
phpxmlxpathsimplexml

SimpleXMLElement find by attribute in array


I'm trying to filter a node from a SimpleXMLElement which is what I receive, there's two nodes: Accessibility and Activity those properties are nested inside my $xml.

I need to get the node data of the node with the id of 'Activity', for example.

What I've tried

  • When I try $xml->symbol it returns the first element of the array that has my two elements, instead of the array

  • When I try $xml->children() it returns the exact same result as what is returned by '$xml'

  • Using Xpath test = $xml->xpath('/symbol'); This returns an empty array, so I don't know how I can look even deeper

The SimpleXml

object(SimpleXMLElement)#137 (1) {
  ["symbol"]=>
  array(2) {
    [0]=>
    object(SimpleXMLElement)#135 (2) {
      ["@attributes"]=>
      array(2) {
        ["viewBox"]=>
        string(9) "0 0 24 24"
        ["id"]=>
        string(13) "accessibility" <--------------- 
      }
    }
    [1]=>
    object(SimpleXMLElement)#142 (2) {
      ["@attributes"]=>
      array(2) {
        ["viewBox"]=>
        string(9) "0 0 24 24"
        ["id"]=>
        string(8) "activity" <--------------- 
      }
    }
  }
}

XML Source

<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg">
    <symbol viewBox="0 0 24 24" id="accessibility">
        <path d="M2 16L2.8 14M6 16L5.2 14M5.2 14L4 11L2.8 14M5.2 14H2.8"/>
        <path d="M20 13L22 10M20 13L18 10M20 13L20 16"/>
        <path d="M8 12L10 10V16"/>
        <path d="M13 12L15 10V16"/>
    </symbol>
    <symbol viewBox="0 0 24 24" id="activity">
        <polyline points="21 14 18 14 15 7 10 17 7 11 5 14 3 14"/>
    </symbol>
</svg>

Solution

  • To select symbol node with attribute id equal to "activity" try XPath

    '//*[name()="symbol" and @id="activity"]'