简体   繁体   中英

how to check if xml file has more than one child values using php

i have xml file $file.xml which includes the following

<?xml version="1.0"?>
<names><name>name1</name><name>name2</name><name>name3</name></names>

i need a way to check if <names> has more than one child <name> meaning that if the file has more than <name>name1</name> whick means that if <name>name2</name> or more exist to call a function.

i have tried the following

    $file = "file.xml";

    $result = file_get_contents($file);

    if(@count(file($result)) > 1) {

    //perform a function
    }

the file_get_contents already gave me the values name1 name2 and name3

but the if(@count(file($result)) > 1) { did nothing

Thanks in advance

Yes its quite possible, you could use xpath in conjunction with this case:

$file = "file.xml";
$xml = simplexml_load_file($file);
$names = $xml->xpath('/names/name');
if(count($names) > 1) {
    //perform a function
    echo 'perform!';
}

Or an alternative with DOMDocument with xpath as well:

$dom = new DOMDocument();
$dom->load($file);

$count = $xpath->evaluate('count(/names/name)');
if($count > 1) {
    echo 'perform!';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM