从PHP中的DOMElement获取特定的子标签 [英] Get a specific child tag from a DOMElement in PHP
本文介绍了从PHP中的DOMElement获取特定的子标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要提取可能是也可能不在当前实体的子标签的内容
输入id =name>
< label>全名:< / 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'] =>全名:
['phone'] =>
)
解决方案
奇怪的是:你已经知道你使用过的答案它在你的脚本中, getElementsByTagName()。
但是这次不用DOMDocument作为上下文节点,但使用输入
DOMElement:
<?php
$ doc = getDoc();
foreach($ doc-> getElementsByTagName('required')as $ e){
$ e = $ e-> parentNode; //这应该是< input>元素
// all< label>作为该< input>的直接子项的元素元素
foreach($ e-> getElementsByTagName('label')as $ l){
echo'label =',$ 1-> nodeValue,\\\\
;
}
}
函数getDoc(){
$ doc = new DOMDocument;
$ doc-> loadxml('< foo>
< input id =name>
< label>全名:< / label>
< required />
< / input>
< input id =phone>
< required />
< / input>
< input id =email/>
< / foo>');
return $ doc;
}
打印 label =全名:
I am walking through a xml definition file and I have a DOMNodeList that I am walking through. I need to extract the contents of a child tag that may or may not be in the current entity
<input id="name">
<label>Full Name:</label>
<required />
</input>
<input id="phone">
<required />
</input>
<input id="email" />
I need to replace ????????????? with something that gets me the contents of the label tag if it exists.
Code:
foreach($dom->getElementsByTagName('required') as $required){
$curr = $required->parentNode;
$label[$curr->getAttribute('id')] = ?????????????
}
Expected Result:
Array(
['name'] => "Full Name:"
['phone'] =>
)
解决方案
Strange thing is: you already know the answer since you've used it in your script, getElementsByTagName().
But this time not with the DOMDocument as context "node" but with the 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;
}
prints label="Full Name:"
这篇关于从PHP中的DOMElement获取特定的子标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文