SimpleXML: Selecting Elements Which Have A Certain Attribute Value

后端 未结 2 1738
半阙折子戏
半阙折子戏 2020-11-22 04:29

In an XML document, I have elements which share the same name, but the value of an attribute defines what type of data it is, and I want to select all of those elements whic

2条回答
  •  滥情空心
    2020-11-22 05:00

    I just made a function to do this for me; it only grabs the first result though. Your mileage may vary.

    function query_attribute($xmlNode, $attr_name, $attr_value) {
      foreach($xmlNode as $node) { 
        if($node[$attr_name] == $attr_value) {
            return $node;
        }
      }
    }
    

    Usage:

    echo query_attribute($MySimpleXmlNode->Customer, "type", "human")->Name;
    

    (For the XML below)

    Sam Jones
    

提交回复
热议问题