PHP的SimpleXML遍历所有子元素及访问特定节点元素和属性

栏目: PHP · 发布时间: 7年前

内容简介:运行结果SimpleXMLElement Object ( [computerbook] => PHP从入门到精通 )SimpleXMLElement Object ( [0] => PHP从入门到精通 )
<?php
header('Content-Type:text/html;charset=utf-8');					//设置编码
/*  创建XML格式的字符串  */
$str = <<<XML
<?xml version='1.0' encoding='gb2312'?>
<object>
  <book>
    <computerbook>PHP从入门到精通</computerbook>
  </book>
  <book>
    <computerbook>PHP项目开发全程实录</computerbook>
  </book>
</object>
XML;
/*  **************************  */
$xml = simplexml_load_string($str);							//创建一个simplexml对象
foreach($xml->children() as $layer_one){							//循环输出根节点
  print_r($layer_one);										//查看节点结构
  echo '<br>';
  foreach($layer_one->children() as $layer_two){					//循环输出第二层根节点
    print_r($layer_two);									//查看节点结构
    echo '<br>';
  }
}
?>

运行结果

SimpleXMLElement Object ( [computerbook] => PHP从入门到精通 )

SimpleXMLElement Object ( [0] => PHP从入门到精通 )

SimpleXMLElement Object ( [computerbook] => PHP项目开发全程实录 )

SimpleXMLElement Object ( [0] => PHP项目开发全程实录 )

———————

PHP的SimpleXML访问特定节点元素和属性

<?php
header('Content-Type:text/html;charset=utf-8');					//设置编码
/*  创建XML格式的字符串  */
$str = <<<XML
<?xml version='1.0' encoding='gb2312'?>
<object name='商品'>
  <book>
    <computerbook>PHP从入门到精通</computerbook>
  </book>
  <book>
    <computerbook name='PHP项目开发全程实录'/>
  </book>
</object>
XML;
/*  **************************  */
$xml = simplexml_load_string($str);								//创建simpleXML对象
echo $xml[name].'<br>';										//输出根元素的属性name
echo $xml->book[0]->computerbook.'<br>';						//输出子元素中computerbook的值
echo $xml->book[1]->computerbook['name'].'<br>';					//输出computerbook的属性值
?>

 运行结果

商品

PHP从入门到精通

PHP项目开发全程实录


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

An Introduction to the Analysis of Algorithms

An Introduction to the Analysis of Algorithms

Robert Sedgewick、Philippe Flajolet / Addison-Wesley Professional / 1995-12-10 / CAD 67.99

This book is a thorough overview of the primary techniques and models used in the mathematical analysis of algorithms. The first half of the book draws upon classical mathematical material from discre......一起来看看 《An Introduction to the Analysis of Algorithms》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

SHA 加密
SHA 加密

SHA 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试