0

I have the following complex, not quite well-structured XML:

<event hometeam="K.Kanepi" awayteam="S.Lisicki" eventName="K.Kanepi-S.Lisicki" date="02/07/2013" time="14:05" datetime="2013-07-02T14:05:00+02:00">
    <subevent title="Match odds" dsymbol="MATCH_ODDS">
        <selection name="home" odds="3.1500" slipURL="URI/en/add-bet/3187-02072013,1"/>
        <selection name="away" odds="1.3500" slipURL="URI/en/add-bet/3187-02072013,2"/>
    </subevent>

I'm trying to parse it using this code:

$total_games = $xml->event->count();

for ($i = 0; $i < $total_games; $i++) {
    echo $xml->event[$i]->subevent.title;

$total games works correctly; however - when I try to parse subevent, I'm unsuccessful in getting the eventName, hometeam, date, etc.

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
timw07
  • 339
  • 2
  • 5
  • 18
  • 4
    Are you using DomDocument, SimpleXML or another library? – Ben Jul 02 '13 at 15:45
  • Appears to be SimpleXML by the syntax. – Sean Bright Jul 02 '13 at 15:48
  • better try to fix the xml instead of tryign to force your DOM library to try and handle mal-formed input. If all it takes is appending `` to that xml string to make it well-formed, then take that easy road. – Marc B Jul 02 '13 at 15:50
  • It _might_ be easier with xpath. Give it a read. – Prasanth Jul 02 '13 at 17:47
  • possible duplicate of [Accessing @attribute from SimpleXML](http://stackoverflow.com/questions/1652128/accessing-attribute-from-simplexml) – hakre Jul 03 '13 at 03:40
  • This XML is neither complex nor unstructured. It's just XML. Every XML parser can deal with it just fine. – hakre Jul 03 '13 at 03:40

1 Answers1

5

To access attributes, you need to use array subscripting instead of class member syntax. This works for me using your XML as input:

<?
    $xml = simplexml_load_file('http://some.url.here/gimme.xml');

    $total_games = $xml->event->count();

    for ($i = 0; $i < $total_games; $i++) {
        echo $xml->event[$i]->subevent['title'];
        //       Note the syntax here ^^^^^^^^^
    }
?>

PHP's Basic SimpleXML usage page is a good resource in this case.

Sean Bright
  • 118,630
  • 17
  • 138
  • 146