如果字段为空 - 显示,否则不显示

时间:2014-03-13 12:13:49

标签: php xml

我正在寻求你的帮助!我想显示其中disconnect_time为空的玩家2和玩家3的名称(因为他们仍然在游戏中)并且不显示玩家1因为他不再在游戏中。

我将如何继续这样做?

我知道通过

取出一个名字
$xml->players->player->name;

但我不知道如何与多个玩家一起做
- 并使用if语句,例如disconnect_time empty == show

<server>
<players>
   <player>
      <name>Player 1</name>
      <connect_time>2014-03-13 09:27</connect_time>
      <disconnect_time>2014-03-13 09:36</disconnect_time>
   </player>
   <player>
      <name>Player 2</name>
      <connect_time>2014-03-13 11:37</connect_time>
      <disconnect_time/>
   </player>
   <player>
      <name>Player 3</name>
      <connect_time>2014-03-13 11:45</connect_time>
      <disconnect_time/>
   </player>
</players>
</server>

非常感谢你提前帮忙!

3 个答案:

答案 0 :(得分:0)

使用此代码

$xml = '<server>
<players>
   <player>
       <name>Player 1</name>
      <connect_time>2014-03-13 09:27</connect_time>
      <disconnect_time>2014-03-13 09:36</disconnect_time>
   </player>
   <player>
      <name>Player 2</name>
      <connect_time>2014-03-13 11:37</connect_time>
      <disconnect_time/>
   </player>
      <player>
      <name>Player 3</name>
      <connect_time>2014-03-13 11:37</connect_time>
      <disconnect_time>2014-03-13 09:36</disconnect_time>
   </player>
   </players>
</server>';
$xml = simplexml_load_string($xml);


 $array = $xml->players->player;
 $newarray = array(); 
foreach($array as $k => $v){ 

     if($v->disconnect_time == ""){ 
        $newarray[] = (string)$v->name;  
     }

}

print_r($newarray); 

输出:

Array ( [0] => Player 2 ) 

答案 1 :(得分:0)

或者,如果您不使用simplexml解析器并使用DOMDocument对象,则可以使用以下命令:

$dom = new DOMDocument;
$dom->loadXML($xml);
$players = $dom->getElementsByTagName('player');
foreach($players as $player):
if($player->getElementsByTagName('disconnect_time')->item(0)->textContent == ''):
        echo $player->getElementsByTagName('name')->item(0)->textContent .' is still connected!';
    endif;
endforeach;

答案 2 :(得分:0)

使用simpleXml

$xml = simplexml_load_string($x); // assume XML in $x

使用xpath而不是循环来获取玩家的名字:

$names = $xml->xpath("/server/players/player[disconnect_time = '']/name");

表达式是选择所有<name>的{​​{1}} - 节点 - 具有空<player> - 节点的节点。这就像SQL for XML。结果将<disconnect_time>存储在数组simpleXml-Elements中。

现在输出:

$names

看到它有效:https://eval.in/119697