Search code examples
phpxmlsimplexml

Need some help with XML parsing


The XML feed is located at: http://xml.betclick.com/odds_fr.xml

I need a php loop to echo the name of the match, the hour, and the bets options and the odds links. The function will select and display ONLY the matchs of the day with streaming="1" and the bets type "Ftb_Mr3".

I'm new to xpath and simplexml.

Thanks in advance.

So far I have:

<?php
$xml_str = file_get_contents("http://xml.betclick.com/odds_fr.xml");
$xml = simplexml_load_string($xml_str);

// need xpath magic
$xml->xpath();

// display

?>

Solution

  • Xpath is pretty simple once you get the hang of it

    you basically want to get every match tag with a certain attribute

    //match[@streaming=1]
    

    will work pefectly, it gets every match tag from underneath the parent tag with the attribute streaming equal to 1

    And i just realised you also want matches with a bets type of "Ftb_Mr3"

    //match[@streaming=1]/bets/bet[@code="Ftb_Mr3"]
    

    This will return the bet node though, we want the match, which we know is the grandparent

    //match[@streaming=1]/bets/bet[@code="Ftb_Mr3"]/../..
    

    the two dots work like they do in file paths, and gets the match.

    now to work this into your sample just change the final bit to

    // need xpath magic
    $nodes = $xml->xpath('//match[@streaming=1]/bets/bet[@code="Ftb_Mr3"]/../..');
    
    foreach($nodes as $node) {
        echo $node['name'].'<br/>';
    }
    

    to print all the match names.