header('Content-Type:text/html;charset=utf-8');//设置编码
/* 创建XML格式的字符串 */
$str = <<
PHP从入门到精通
PHP项目开发全程实录
XML;
/* ************************** */
$xml = simplexml_load_string($str);//创建一个simplexml对象
foreach($xml->children() as $layer_one){//循环输出根节点
print_r($layer_one);//查看节点结构
echo '
';
foreach($layer_one->children() as $layer_two){//循环输出第二层根节点
print_r($layer_two);//查看节点结构
echo '
';
}
}
?>
运行结果
SimpleXMLElement Object ( [computerbook] => PHP从入门到精通 )
SimpleXMLElement Object ( [0] => PHP从入门到精通 )
SimpleXMLElement Object ( [computerbook] => PHP项目开发全程实录 )
SimpleXMLElement Object ( [0] => PHP项目开发全程实录 )
---------------------
PHP的SimpleXML访问特定节点元素和属性
header('Content-Type:text/html;charset=utf-8');//设置编码
/* 创建XML格式的字符串 */
$str = <<
PHP从入门到精通
XML;
/* ************************** */
$xml = simplexml_load_string($str);//创建simpleXML对象
echo $xml[name].'
';//输出根元素的属性name
echo $xml->book[0]->computerbook.'
';//输出子元素中computerbook的值
echo $xml->book[1]->computerbook['name'].'
';//输出computerbook的属性值
?>
运行结果
商品
PHP从入门到精通
PHP项目开发全程实录