gpt4 book ai didi

php - 从 PHP 中的 DOMElement 获取特定的子标签

转载 作者:可可西里 更新时间:2023-11-01 13:18:34 26 4
gpt4 key购买 nike

我正在遍历一个 xml 定义文件,并且有一个正在遍历的 DOMNodeList。我需要提取子标记的内容,该子标记可能存在于当前实体中,也可能不存在

<input id="name">
<label>Full Name:</label>
<required />
</input>
<input id="phone">
<required />
</input>
<input id="email" />

我需要替换??????????????如果它存在。

代码:

foreach($dom->getElementsByTagName('required') as $required){
$curr = $required->parentNode;

$label[$curr->getAttribute('id')] = ?????????????
}

预期结果:

Array(
['name'] => "Full Name:"
['phone'] =>
)

最佳答案

奇怪的是:你已经知道答案了,因为你已经在你的脚本中使用了它,getElementsByTagName() .
但这次不是将 DOMDocument 作为上下文“节点”,而是将 input DOMElement:

<?php
$doc = getDoc();
foreach( $doc->getElementsByTagName('required') as $e ) {
$e = $e->parentNode; // this should be the <input> element
// all <label> elements that are direct children of this <input> element
foreach( $e->getElementsByTagName('label') as $l ) {
echo 'label="', $l->nodeValue, "\"\n";
}
}

function getDoc() {
$doc = new DOMDocument;
$doc->loadxml('<foo>
<input id="name">
<label>Full Name:</label>
<required />
</input>
<input id="phone">
<required />
</input>
<input id="email" />
</foo>');
return $doc;
}

打印 label="Full Name:"

关于php - 从 PHP 中的 DOMElement 获取特定的子标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3816806/

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