Php获取xml中的节点值
XML: test_xml2.xml
<?xml version="1.0" encoding="UTF-8"?>
<friends_get_response list="true" xmlns="http://api.xiaonei.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://api.xiaonei.com/1.0/ http://api.xiaonei.com/1.0/xiaonei.xsd">
<uid>200032219</uid>
<uid>84525914</uid>
<uid>12345689</uid>
<uid>98765432</uid>
</friends_get_response>
PHP代码1:
<?php
$doc=new DOMDocument();
$doc->load('test_xml2.xml');
$productProfile=$doc->getElementsByTagName('friends_get_response');
echo '<pre/>';
foreach($productProfile as $profile)
{
//$productNames = $profile->getElementsByTagName("uid");
//$productName = $productNames->item(0)->nodeValue;
//echo $productName;
echo $profile->nodeValue;
}
?>
结果: 这样nodeValue,直接把节点中的所有值都取出来
200032219
84525914
12345689
98765432
PHP 代码2:
<?php
$doc = new DOMDocument();
$doc->load('test_xml2.xml');
$xiaoNei = $doc->getElementsByTagName( "friends_get_response" );
$i=0;
foreach($xiaoNei as $key ){
$uid = $key->getElementsByTagName( "uid" );
foreach ( $uid as $param) {
echo $param -> nodeValue .'<br />';
}
}
?>
结果:这是得到friends_get_response->uid 节点的值
200032219
84525914
12345689
98765432
XML2: test_xml4.xml
<?xml version='1.0' standalone='yes'?>
<test>
<a>aa</a>
<b>
<bb>bb1</bb>
<bb>
<bbb>bbb1</bbb>
<bbb>bbb2</bbb>
</bb>
</b>
<c>cc</c>
<d>
<f> ff </f>
</d>
</test>
PHP代码:
<?php
echo '<pre/>';
$doc = new DOMDocument();
$doc->load( 'test_xml4.xml' );
$xiaoNei = $doc->getElementsByTagName( "test" );
foreach( $xiaoNei as $v)
{
echo $v->nodeValue.'<br />';
}
?>
结果为: 使用nodeValue直接就得到test节点下面的 多层子节点的值
aa
bb1
bbb1
bbb2
cc
ff
/***************************************/
PHP代码:
<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El ActÓr</actor>
</character>
</characters>
<plot>
So, this language. It's like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
$xml = simplexml_load_string($xmlstr);
echo $xml->movie[0]->title;
echo '<br>';
$arr = $xml->movie[0]->characters[0]->character;
echo '<br>';
foreach($arr as $kk => $vv)
{
echo $vv->name;
echo '<br/>';
}
?>
结果为:
$xml->movie[0]->title:
PHP: Behind the Parser
$vv->name: Ms. Coder
Mr. Coder