简体   繁体   English

使用DomDocument PHP获取子节点XML

[英]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 我已经阅读了DomDocument PHP的说明,并尝试从xml文件中获取特定的孩子,这里是示例

<?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. 以及如何使用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. DOMDocument::getElementsByTagName()的参数是单个节点名称,并且始终返回节点列表。 For more complex and flexible expressions you need to use XPath: 对于更复杂和灵活的表达式,您需要使用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"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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