繁体   English   中英

使用DomDocument PHP获取子节点XML

[英]Get Child Node XML With DomDocument PHP

我已经阅读了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>

我想要的是,假设我要访问索引标签的权限值标签,那么该怎么做? 以及如何使用domdocument php检查权限标签是否存在于索引标签上。

在这里,我做了什么

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

DOMDocument::getElementsByTagName()的参数是单个节点名称,并且始终返回节点列表。 对于更复杂和灵活的表达式,您需要使用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); 

输出:

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

暂无
暂无

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

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