gpt4 book ai didi

PHP + XPath 查询获取子节点及其值

转载 作者:数据小太阳 更新时间:2023-10-29 02:56:08 24 4
gpt4 key购买 nike

我有一个 XML 文件 record.xml,它看起来像:

<record>
<name>john</name>
<gender>male</gender>
<subject>mathematics, english, science</subject>
</record>
<record>
<name>jamie</name>
<gender>female</gender>
<subject>mathematics, science</subject>
</record>
<record>
<name>jack</name>
<gender>male</gender>
<subject>social-science, english</subject>
</record>

我想编写一个 xpath 查询,它将返回 <record> 的所有子节点名称以及关联数组中所有这些子节点的值。

For Ex.:

For above XML file Output array should be-

array{
[0] => array{
[name] = 'john',
[gender] = 'male',
[subject] = 'mathematics, english, science'
}
[1] => array{
[name] = 'jamie',
[gender] = 'female',
[subject] = 'mathematics, science'
}
[2] => array{
[name] = 'jack',
[gender] = 'male',
[subject] = 'social-science, english'
}
}

下面是我写的部分代码返回所有<record>子节点值而不是它们的节点名称。

    .......
.......
$xmldoc = new DOMDocument();
$xmldoc->load('record.xml');
$xpathvar = new Domxpath($xmldoc);
$res = $xpathvar->query('//record');
foreach($res as $data){
//$data do not contain node values
$arr[] = $data->textContent;
}
//process $arr to get required format
.....
.....

我只想要一个 Xpath 查询,它将返回子节点名称及其值。

最佳答案

问题是记录,因为节点只是节点层次结构的一部分。您得到的是所有记录,但是您还想下降并从记录的子节点获取数据。一个非常具体的例子是:

<?php     
$xmldoc = new DOMDocument();
$xmldoc->load('record.xml');
$xpathvar = new Domxpath($xmldoc);
$res = $xpathvar->query('//record');
foreach($res as $data){
$narr = [];
foreach ($data->childNodes as $cnode) {
$narr[$cnode->nodeName] = $cnode->nodeValue;
}
$arr[] = $narr;

}
print_r($arr);

应该输出如下内容:

Array
(
[0] => Array
(
[name] => john
[gender] => male
[subject] => mathematics, english, science
)

[1] => Array
(
[name] => jamie
[gender] => female
[subject] => mathematics, science
)

[2] => Array
(
[name] => jack
[gender] => male
[subject] => social-science, english
)

)

注意:此解决方案非常具体,如果您有额外的嵌套层次结构(我建议您这样做以存储多个主题),则可能会中断。

关于PHP + XPath 查询获取子节点及其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37973058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com