php如何取下面xml文件中的数据?

 我来答
匿名用户
2014-05-21
展开全部
给你一个列子..自己琢磨去吧.这是DOM方式读取PHP代码<?php // DOM方式编写XML$books = array(); $books [] = array(
'title' => 'java book',
'author' => 'skygao',
'desn' => "very good !!!"
);
$books [] = array(
'title' => 'php oop',
'author' => 'gaoluofeng',
'desn' => "good very good"
);
$books [] = array(
'title' => 'c/c++ book',
'author' => 'gaoluofeng',
'desn' => "this is a ok !!"
); $doc = new DOMDocument(); $doc->formatOutput = true; $r = $doc->createElement( "books" );
$doc->appendChild( $r );foreach( $books as $book )
{
$b = $doc->createElement( "book" ); $author = $doc->createElement( "author" );
$author->appendChild( $doc->createTextNode( $book['author'] ) );
$b->appendChild( $author ); $title = $doc->createElement( "title" );
$title->appendChild( $doc->createTextNode( $book['title'] ) );
$b->appendChild( $title ); $desn = $doc->createElement( "desn" );
$desn->appendChild($doc->createTextNode( $book['desn'] ));
$b->appendChild( $desn );
$r->appendChild( $b );
} echo $doc->saveXML(); exit;
// DOM方式解析XML
$xml_file = './test.xml';$dom = new DOMDocument();
$dom->load($xml_file);$obj_arr = $dom->getElementsByTagName('user');
$user_arr = array(); foreach( $obj_arr as $k=>$user )
{

$name = $user->getElementsByTagName( "name" );
$user_arr[$k]['name'] = $name->item(0)->nodeValue;

$age = $user->getElementsByTagName( "age" );
$user_arr[$k]['age'] = $age->item(0)->nodeValue;

}
var_dump($user_arr);exit;
?>XML文件<?xml version="1.0" encoding="utf-8" ?>
<root>
<user>
<name>张三</name>
<age>30</age>
</user> <user>
<name>李四</name>
<age>20</age>
</user>
<user>
<name>王麻子</name>
<age>10</age>
</user>
</root>
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式