首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

SimpleXMLElement::children

(PHP 5 >= 5.0.1, PHP 7)

SimpleXMLElement :: children - 查找给定节点的子节点

描述

代码语言:javascript
复制
public SimpleXMLElement SimpleXMLElement::children ([ string $ns [, bool $is_prefix = false ]] )

该方法找到元素的子元素。结果遵循正常的迭代规则。

注意:SimpleXML已经为大多数方法添加了迭代属性。它们不能使用var_dump()或其他可以检查对象的东西来查看。

参数

ns

一个XML命名空间。

is_prefix

如果is_prefix为TRUE,则ns将被视为前缀。 如果FALSE,则ns将被视为一个名称空间URL。

返回值

返回一个SimpleXMLElement元素,无论节点是否有子节点。

更新日志

版本

描述

5.2.0

添加了可选参数is_prefix。

例子

Example#1 遍历一个child () 伪数组

代码语言:javascript
复制
<?php
$xml?=?new?SimpleXMLElement(
'<person>
?<child?role="son">
??<child?role="daughter"/>
?</child>
?<child?role="daughter">
??<child?role="son">
???<child?role="son"/>
??</child>
?</child>
</person>');

foreach?($xml->children()?as?$second_gen)?{
????echo?'?The?person?begot?a?'?.?$second_gen['role'];

????foreach?($second_gen->children()?as?$third_gen)?{
????????echo?'?who?begot?a?'?.?$third_gen['role']?.?';';

????????foreach?($third_gen->children()?as?$fourth_gen)?{
????????????echo?'?and?that?'?.?$third_gen['role']?.
????????????????'?begot?a?'?.?$fourth_gen['role'];
????????}
????}
}
?>

上面的例子将输出:

代码语言:javascript
复制
The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

示例#2 使用名称空间

代码语言:javascript
复制
<?php
$xml?=?'<example?xmlns:foo="my.foo.urn">
??<foo:a>Apple</foo:a>
??<foo:b>Banana</foo:b>
??<c>Cherry</c>
</example>';

$sxe?=?new?SimpleXMLElement($xml);

$kids?=?$sxe->children('foo');
var_dump(count($kids));

$kids?=?$sxe->children('foo',?TRUE);
var_dump(count($kids));

$kids?=?$sxe->children('my.foo.urn');
var_dump(count($kids));

$kids?=?$sxe->children('my.foo.urn',?TRUE);
var_dump(count($kids));

$kids?=?$sxe->children();
var_dump(count($kids));
?>
代码语言:javascript
复制
int(0)
int(2)
int(2)
int(0)
int(1)

注意

无论当前节点是否有子节点,SimpleXMLElement :: children()都会返回一个节点对象。在返回值上使用count()来查看是否有任何子节点。从PHP 5.3.0开始,可以使用SimpleXMLElement :: count()来代替。

扩展内容

  • SimpleXMLElement :: count() - 计算元素的子元素
  • count() - 统计数组中的所有元素或对象中的某个元素

← SimpleXMLElement::attributes

SimpleXMLElement::__construct →

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com