SimpleXML: Selecting Elements Which Have A Certain Attribute Value

后端 未结 2 1639
半阙折子戏
半阙折子戏 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:01

    Try this XPath:

    /object/data[@type="me"]
    

    Which reads as:

    • Select (/) children of the current element called object
    • Select (/) their children called data
    • Filter ([...]) that list to elements where ...
      • the attribute type (the @ means "attribute")
      • has the text value me

    So:

    $myDataObjects = $simplexml->xpath('/object/data[@type="me"]');
    

    If object is not the root of your document, you might want to use //object/data[@type="me"] instead. The // means "find all descendents" rather than "find all children".

提交回复
热议问题