简体   繁体   中英

Get Child Node XML With DomDocument PHP

I have read instruction of DomDocument PHP, and try to get specific child from xml file, here the example

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <methods>
        <index>
            <title>User</title>
            <meta_description>Description part</meta_description>
            <meta_keywords>keywords parts</meta_keywords>
            <permissions>permissions part</permissions>
            <layout>layout parts</layout>
            <css>css parts</css>
        </index>
        <update>
            <title>update part</title>
            <permissions>update_user</permissions>
        </update>
    </methods>
</configuration>

What I want is, let say I want to access permissions value tag of index tag, then how to do that? And how to check if permissions tag is exists on index tag with domdocument php.

Here, what I have done

$xml = new DOMDocument();
    $xml->load(__DIR__ . DIRECTORY_SEPARATOR . 'configuration.xml');
    $configurations['title'] = $xml->getElementsByTagName('index title')->nodeValue;
    print_r($configurations);

The argument of DOMDocument::getElementsByTagName() is a single node name and it always returns a node list. For more complex and flexible expressions you need to use XPath:

$dom = new DOMDocument();
$dom->load(__DIR__ . DIRECTORY_SEPARATOR . 'configuration.xml');
$xpath = new DOMXPath($dom);

$configurations['title'] = $xpath->evaluate('string(//index/title)');
var_dump($configurations); 

Output:

array(1) {
  ["title"]=>
  string(4) "User"
}

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