我正在遍历一个 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/