PHP: Check if XML node exists with attribute

前端 未结 4 471
轻奢々
轻奢々 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:

    <?php
    
    $xmlDocument = new DOMDocument();
    
    $nameToFind = "Shiny Red";
    
    if ($xmlDocument->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;
    }
    
    ?>
    
    0 讨论(0)
  • 2020-12-06 07:55

    This XPath expression:

           /*/*/building[@name = 'Shiny Red']

    selects the element named building the value of whose name attribute is 'Shiny Red' and that is a child of a child of the top element.

    Probably in PHP there is a way to evaluate XPath expressions, then just evaluate the above XPath expression and use the result.

    0 讨论(0)
  • 2020-12-06 08:00

    I'd suggest the following (PHP using ext/simplexml and XPath):

    $name = 'Shiny Red';
    $xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?>
    <targets>
      <showcases>
        <building name="Big Blue" />
        <building name="Shiny Red" />
        <building name="Mellow Yellow" />
      </showcases>
    </targets>');
    $nodes = $xml->xpath(sprintf('/targets/showcases/building[@name="%s"]', $name);
    if (!empty($nodes)) {
        printf('At least one building named "%s" found', $name);
    } else {
        printf('No building named "%s" found', $name);
    }
    
    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题