Show attribute value 0 if its coming null (PHP)(XML)

207
July 16, 2017, at 4:32 PM
 $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>

Right now i am getting Fatal error as i dont have Odds data in 2nd game. If i dont have any 5Dimes odds in any Sportsbook. i just want to show value null there.

Fatal error: Call to a member function attributes() on null

Result

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

Thanks

Answer 1

Here's my solution:

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;
}

Output:

Time: 1:45 PM LineType: 2<br/>
Time: 1:45 PM LineType: NULL<br/>
Time: 1:46 PM LineType: 4<br/>
Rent Charter Buses Company
READ ALSO
How make group of the JSON data of same key

How make group of the JSON data of same key

I am working in phpI have the JSON data in which muliple data comes some data have two same keys as shown below

213
How to encrypt xml document type in browser game online? [on hold]

How to encrypt xml document type in browser game online? [on hold]

i have a php file that can decrypt xml/conf document typeBut when i re-encrypt them again, it's fail!! Could you show me where is wrong?? Here my code:

260
update existing array record if already exists in database else insert into database using array

update existing array record if already exists in database else insert into database using array

i am getting error while updating my sales order using for each

286