PHP DOM:如何通过标签名称以优雅的方式获取子元素? [英] PHP DOM: How to get child elements by tag name in an elegant manner?
问题描述
DOMElement :: getElementsByTagName($ name)
,但它返回所有后代与该名称,而不仅仅是直接的孩子。还有属性 DOMNode :: $ childNodes
,但(1)它包含节点列表,而不是元素列表,即使我设法将列表项转换为元素(2 )我仍然需要检查所有这些名称。是否真的没有优雅的解决方案来获得一些具体名字的孩子,或者我在文档中缺少某些东西? 一些例证:
<?php
DOMDocument();
$ document-> loadXML(<<< EndOfXML
< a>
< b> 1< / b>
< b> b>
< c>
< b> 3< / b>
< b> 4< / b>
< / c>
< ; / a>
EndOfXML
);
$ bs = $ document
- > getElementsByTagName('a')
- >项(0)
- > getElementsByTagName('b' ;
foreach($ bs as $ b){
echo $ b-> nodeValue。 \\\
;
}
//返回:
// 1
// 2
// 3
// 4
/ /我只想获得:
// 1
// 2
?>
简单迭代过程
$ parent = $ p-> parentNode;
foreach($ parent-> childNodes as $ pp){
if($ pp-> nodeName =='p'){
if strlen($ pp-> nodeValue)){
echo{$ pp-> nodeValue} \\\
;
}
}
}
I'm parsing some XML with PHP DOM extension in order to store the data in some other form. Quite unsurprisingly, when I parse an element I pretty often need to obtain all children elements of some name. There is the method DOMElement::getElementsByTagName($name)
, but it returns all descendants with that name, not just immediate children. There is also the property DOMNode::$childNodes
but (1) it contains node list, not element list, and even if I managed to turn the list items into elements (2) I'd still need to check all of them for the name. Is there really no elegant solution to get only the children of some specific name or am I missing something in the documentation?
Some illustration:
<?php
DOMDocument();
$document->loadXML(<<<EndOfXML
<a>
<b>1</b>
<b>2</b>
<c>
<b>3</b>
<b>4</b>
</c>
</a>
EndOfXML
);
$bs = $document
->getElementsByTagName('a')
->item(0)
->getElementsByTagName('b');
foreach($bs as $b){
echo $b->nodeValue . "\n";
}
// Returns:
// 1
// 2
// 3
// 4
// I'd like to obtain only:
// 1
// 2
?>
simple iteration process
$parent = $p->parentNode;
foreach ( $parent->childNodes as $pp ) {
if ( $pp->nodeName == 'p' ) {
if ( strlen( $pp->nodeValue ) ) {
echo "{$pp->nodeValue}\n";
}
}
}
这篇关于PHP DOM:如何通过标签名称以优雅的方式获取子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!