Denoteone
Denoteone

Reputation: 4055

SimpleXML parsing using element text

I am having an issue wrapping my head around the SimpleXML syntax.

I am trying to echo a few pieces of info I pull out of a larger xml document based on a predefined value DELN:

$mytimes= simplexml_load_file('http://www.bart.gov/dev/eta/bart_eta.xml');


$freemont = $mytimes->station->abbr[DELN]->eta->destination[freemont]->estimate;
$millbrae = $mytimes->station->abbr[DELN]->eta->destination[millbrae]->estimate;
$richmond = $mytimes->station->abbr[DELN]->eta->destination[richmond]->estimate;

My XML:

<station>
<name>El Cerrito del Norte</name>
   <abbr>DELN</abbr>
   <date>11/30/2012</date>
   <time>07:41:02 AM PST</time>
    <eta>
         <destination>Fremont</destination>
         <estimate>14 min, 29 min, 44 min</estimate>
    </eta>
    <eta>
          <destination>Millbrae</destination>
          <estimate>6 min, 21 min, 36 min</estimate>
    </eta>
    <eta>
          <destination>Richmond</destination>
          <estimate>4 min, 10 min, 17 min</estimate>
    </eta>
</station>

Let me know if I need to provide more info. Thanks.

Upvotes: 0

Views: 60

Answers (1)

lupatus
lupatus

Reputation: 4248

First - I suppose you're not defining DELN constant, probably you should use a string ('DELN'). Same with freemont, millbrae and richmont. The problem is not only SimpleXML syntax, basically its misunderstanding of XML structure that you want to read (abbr is not in straight path with eta, same with destination and estimate). Anyway - xpath will be your friend here:

$fremont = $mytimes->xpath('//station/eta/estimate[../../abbr/text()=\'DELN\' and ../destination/text()=\'Fremont\']');
$millbrae = $mytimes->xpath('//station/eta/estimate[../../abbr/text()=\'DELN\' and ../destination/text()=\'Millbrae\']');
$richmond = $mytimes->xpath('//station/eta/estimate[../../abbr/text()=\'DELN\' and ../destination/text()=\'Richmond\']');

then you can do:

foreach ($fremont as $value) echo $value;

or just

if (count($fremont) > 0) echo $fremont[0];

Upvotes: 1

Related Questions