我遇到了围绕SimpleXML语法的问题。
我试图回应一些基于预定义值DELN从较大的xml文档中提取的信息:
$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;
我的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>
如果我需要提供更多信息,请告诉我。感谢。
答案 0 :(得分:1)
首先 - 我想你没有定义DELN常量,可能你应该使用一个字符串('DELN')。与freemont,millbrae和richmont相同。问题不仅在于SimpleXML语法,基本上是你想要阅读的XML结构的误解(abbr与eta没有直接路径,与目标和估计相同)。无论如何 - xpath将成为你的朋友:
$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\']');
然后你可以这样做:
foreach ($fremont as $value) echo $value;
或只是
if (count($fremont) > 0) echo $fremont[0];