程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP基礎知識 >> Php獲取xml中的節點值 實現代碼

Php獲取xml中的節點值 實現代碼

編輯:PHP基礎知識
 

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&#211;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

 

這裡是簡單的方法,當然獲取xml中節點值,還有很多方法 如:SimpleXML functions 等等

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved