0

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.

1 Answer 1

1

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];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks xpath was exactly what I was looking for. This makes it much easier to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.