php simplexml get a specific item based on the value of a field

前端 未结 2 604
一个人的身影
一个人的身影 2020-12-02 02:37

Is there a way i can get a specific item with SimpleXML ?

For example, i would like to get the title of an item having ID set to 12437 with this example xml :

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 03:01

    You want to use Xpath for this. It's basically exactly the same as outlined in SimpleXML: Selecting Elements Which Have A Certain Attribute Value but in your case you're not deciding on an attribute value but on an element value.

    However in Xpath for both the element you're looking for is the parent.So formulating the xpath expression is kind of straight forward:

    // Here we find the item element that has the child  element
    //   with node-value "12437".
    
    list($result) = $data->xpath('(//items/item[id = "12437"])[1]');
    $result->asXML('php://output');
    

    Output (beautified):

    
      title of 12437
      12437
    
    

    So let's see the heart of this xpath query again:

    //items/item[id = "12437"]
    

    It's written as: Select all elements that are a children of any elements which on their own have a child element named with the value "12437".

    And now with the missing stuff around:

    (//items/item[id = "12437"])[1]
    

    The parenthesis around says: From all these elements, pick the first one only. Depending on your structure this might or might not be necessary.

    So here is the full usage example and online demo:

    
      
        title of 43534
        43534
      
      
        title of 12437
        12437
      
      
        title of 7868
        7868
      
    
    XML;
    
    $data = new SimpleXMLElement($str);
    
    // Here we find the item element that has the child  element
    //   with node-value "12437".
    
    list($result) = $data->xpath('(//items/item[id = "12437"])[1]');
    $result->asXML('php://output');
    

    So what you call a field in your questions title is by the book a child-element. Keep this in mind when searching for more complicated xpath queries that get you what you're looking for.

提交回复
热议问题