PHP: Check if XML node exists with attribute

前端 未结 4 470
轻奢々
轻奢々 2020-12-06 07:19

I can\'t seem to figure this one out. I have the following XML file:



  
           


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 08:01

    if I understand that correctly, doesn't that only test the first node?

    Yes. So if you want to use DOM methods like that one, you'll have to do it in a loop. eg.:

    $buildings= $xdoc->getElementsByTagName('building');
    foreach ($buildings as $building)
        if ($building->getAttribute('name')==$name)
            return true;
    return false;
    

    With XPath you can eliminate the loop, as posted by Dimitre and sgehrig, but you'd have to be careful about what characters you allow to be injected into the XPath expression (eg. $name= '"]' will break the expression).

提交回复
热议问题