PHP: Check if XML node exists with attribute

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

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



  
           


        
4条回答
  •  误落风尘
    2020-12-06 07:52

    Okay, looks like XPath was what I wanted. Here's what I came up with that does what I want:

    load('file.xml')) {
            if (checkIfBuildingExists($xmlDocument, $nameToFind)) {
            echo "Found a red building!";
        }
    }
    
    function checkIfBuildingExists($xdoc, $name) {
        $result = false;
        $xpath = new DOMXPath($xdoc);
        $nodeList = $xpath->query('/targets/showcases/building', $xdoc);
        foreach ($nodeList as $node) {
            if ($node->getAttribute('name') == $name) {
                $result = true;
            }
        }
        return $result;
    }
    
    ?>
    

提交回复
热议问题