如果属性值为null(PHP),则显示属性值0(XML)

时间:2017-07-16 08:31:54

标签: php arrays xml

 $xml_data = simplexml_load_file('demo.xml');
 foreach ($xml_data->Game as $game) {
 $t = $game['Time'];
 $odds = $game->xpath('SportsBook[@Name="5Dimes"]/Odds');
 if(isset($odds)){
 $valueLT=$odds[0]->attributes()->LineType;
 echo 'Time: ' . $t . ' LineType: '.$valueLT
 . '<br/>' . PHP_EOL;
 }
 }

demo.xml

 <GameOdds SportsCode="MLB">
 <Game Code="121" Date="07/06/2017" Time="1:45 PM">
 <SportsBook ID="5" Name="5Dimes">
 <Odds LineType="2"  LastUpdated="10"  />
 </SportsBook>
 <SportsBook ID="5" Name="3Dimes">
 <Odds LineType="3"  LastUpdated="20"  />
 </SportsBook> </Game>
 <Game Code="121" Date="07/06/2017" Time="1:45 PM">
 <SportsBook ID="5"  Name="5Dimes" />
 <SportsBook ID="5" Name="3Dimes">
 <Odds LineType="3"  LastUpdated="20"  />
 </SportsBook> </Game>
 <Game Code="122" Date="07/02/2017" Time="1:46 PM">
 <SportsBook ID="2" Name="5Dimes">
 <Odds LineType="4"  LastUpdated="10"  />
 </SportsBook>
 <SportsBook ID="6" Name="3Dimes">
 <Odds LineType="36"  LastUpdated="30"  />
 </SportsBook> 
 </Game></GameOdds>

现在我得到致命错误,因为我在第二场比赛中没有赔率数据。如果我在任何体育博彩中都没有任何5Dimes赔率。我只想在那里显示值null。

  

致命错误:在null

上调用成员函数attributes()

结果

Time: 1:45 PM LineType:2
Time: 1:45 PM LineType:0
Time: 1:46 PM LineType:4

由于

1 个答案:

答案 0 :(得分:1)

这是我的解决方案:

A

输出:

foreach ($xml_data->Game as $game) {
    $t = $game['Time'];
    $odds = $game->xpath('SportsBook[@Name="5Dimes"]/Odds');
    //var_dump($odds); - you will see 
    // it's empty array if there's no `Odds` tags

    // Some default value
    $valueLT = 'NULL';

    // add a strict check if exactly `$odds[0]` exists in `$odds`
    if(!empty($odds[0])) {
        // get value from attribute
        $valueLT = $odds[0]->attributes()->LineType;
    }

    echo 'Time: ' . $t . ' LineType: '.$valueLT . '<br/>' . PHP_EOL;
}