从xml获取特定数据 - > PHP的?

时间:2012-09-05 12:23:14

标签: php xml

我想从以下xml中获取foreach循环:

<?xml version="1.0" encoding="ISO-8859-1"?>
<data>
  <players>
    <player id="1">4</player>
    <player id="2">3</player>
  </players>
  <chats>
    <chat playerid="2">Some chat here...</chat>
    <chat playerid="1">skfgjh kjgh fdskgjhdf kgjhdf gkjd gkjdfhg dkfjhg</chat>
  </chats>
</data>

我希望有一个玩家和一个玩家聊天,但似乎无法解决这个问题......我也想要这些属性并且不知道如何?

以下是我的尝试:

$userXML = simplexml_load_file('xml_chats/0^0.xml') or die ("error");  

foreach($userXML->chats as $nchats){ 
    echo $nchats->chat.'<br>';     
} 

我做错了什么,我怎么能做到这一点?

提前致谢: - )

2 个答案:

答案 0 :(得分:0)

您可以尝试使用xpath方法选择您感兴趣的节点:

$xml = simplexml_load_string($xml);
$chats = $xml->xpath('/data/chats/chat');    
$players = $xml->xpath('/data/players/player');

或者你可以使用simplexml的魔术映射到这样的节点:

foreach ($xml->players->player as $player) { ... }
foreach ($xml->chats->chat as $chat) { ... }

答案 1 :(得分:0)

试试这个

$xml=simplexml_load_file(filename);



foreach($xml->chats as $nchats){ 
    foreach($nchats as $chat)
    {
    echo $nchats->chat.'<br>';     
    foreach($chat->attributes() as $key=>$attrib)
    {
     echo $key."=>".$attrib.'<br>';
    }
    }
}