php解析xml简单实例

php文件代码:

<?php
header("content-type:text/html;charset=utf-8");
$dom = new DOMDocument(); 
$dom->load("1.xml");
$messages = $dom->getElementsByTagName('mess'); 
foreach ($messages as $book) 
{ 
    //get name
    $name = $book->getAttribute('name'); 
     
    //get user id
    $nodeAuth = $book->getElementsByTagName('userID'); 
    $strAuth = $nodeAuth->item(0)->nodeValue; 
 
    //get time
    $nodePub = $book->getElementsByTagName('time'); 
    $strtime = $nodePub->item(0)->nodeValue; 
 
    //get MB
    $nodemess = $book->getElementsByTagName('MB'); 
    $strmess = $nodemess->item(0)->nodeValue;        
     
    //save data 
    $arrInfo['name'] = $name; 
    $arrInfo['userID'] = $strAuth; 
    $arrInfo['time'] = $strtime; 
    $arrInfo['MB'] = $strmess; 
 
    //save info 
    $arrInfos[] = $arrInfo; 
} 
 print_r($arrInfos);   
?>

xml内容:

<Message>
<mess name="jokn">
<userID>328496647</userID>
<time>2009/3/12</time>
<MB>命名不能用保留字,不能用空格</MB>
</mess>
<mess name="李星">
<userID>512385123</userID>
<time>2008/02/02</time>
<MB>加我解决</MB>
</mess>
<mess name="abce">
<userID>843216515</userID>
<time>2009/01/28</time>
<MB>QQ号在下边</MB>
</mess>
<mess name="open">
<userID>55123546</userID>
<time>1989/08/09</time>
<MB>QQ是328496647</MB>
</mess>
</Message>

运行php文件后显示内容将如下(返回的是一数组):

   Array
(
    [0] => Array
        (
            [name] => jokn
            [userID] => 328496647
            [time] => 2009/3/12
            [MB] => 命名不能用保留字,不能用空格
        )

    [1] => Array
        (
            [name] => 李星
            [userID] => 512385123
            [time] => 2008/02/02
            [MB] => 加我解决
        )

    [2] => Array
        (
            [name] => abce
            [userID] => 843216515
            [time] => 2009/01/28
            [MB] => QQ号在下边
        )

    [3] => Array
        (
            [name] => open
            [userID] => 55123546
            [time] => 1989/08/09
            [MB] => QQ是328496647
        )

)

你可能感兴趣的:(php解析xml简单实例)