2

I know that this is a duplicate, but I couldn't apply the answer on this one: LINK I can parse the XML without the xmlns, but the feed I'm parsing from is using it so...

The WORKING XML:

<DPS>
<Buses>
<DpsBus>
<SiteId>9520</SiteId>
<StopAreaNumber>75821</StopAreaNumber>
<TransportMode>BUS</TransportMode>
<StopAreaName>Södertälje centrum</StopAreaName>
<LineNumber>754</LineNumber>
<Destination>Geneta (Scaniarinken)</Destination>
<TimeTabledDateTime>2013-10-31T16:08:00</TimeTabledDateTime>
<ExpectedDateTime>2013-10-31T16:08:00</ExpectedDateTime>
<DisplayTime>0 min</DisplayTime>
</DpsBus>
</Buses>
</DPS>

The NON-WORKING XML

<DPS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www1.sl.se/realtidws/">
<Buses>
<DpsBus>
<SiteId>9520</SiteId>
<StopAreaNumber>75821</StopAreaNumber>
<TransportMode>BUS</TransportMode>
<StopAreaName>Södertälje centrum</StopAreaName>
<LineNumber>754</LineNumber>
<Destination>Geneta (Scaniarinken)</Destination>
<TimeTabledDateTime>2013-10-31T16:08:00</TimeTabledDateTime>
<ExpectedDateTime>2013-10-31T16:08:00</ExpectedDateTime>
<DisplayTime>0 min</DisplayTime>
</DpsBus>
</Buses>
</DPS>

PHP

$xmldata = '<DPS xmlns:xsi="..."';
$xml = simplexml_load_string($xmlData);
$arrLines = $xml->xpath('/DPS/Buses/DpsBus[TransportMode="BUS"]');
foreach($arrLines as $line) {
    echo $line->LineNumber.'<br>';
}

Any ideas here? Thanks!

Community
  • 1
  • 1
Stichy
  • 1,497
  • 3
  • 16
  • 27
  • Please define working. Those two files have different XML tags so they should not work the same. The behavior you describe looks actually technically correct. – hakre Nov 02 '13 at 14:27

1 Answers1

1

Register the namespace via registerXPathNamespace() and update the XPath: /r:DPS/r:Buses/r:DpsBus[r:TransportMode="BUS"]

Then your updated PHP code:

<?php
$xmlData = <<<XML
<?xml version="1.0"?>
<DPS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www1.sl.se/realtidws/">
  <Buses>
    <DpsBus>
      <SiteId>9520</SiteId>
      <StopAreaNumber>75821</StopAreaNumber>
      <TransportMode>BUS</TransportMode>
      <StopAreaName>Södertälje centrum</StopAreaName>
      <LineNumber>754</LineNumber>
      <Destination>Geneta (Scaniarinken)</Destination>
      <TimeTabledDateTime>2013-10-31T16:08:00</TimeTabledDateTime>
      <ExpectedDateTime>2013-10-31T16:08:00</ExpectedDateTime>
      <DisplayTime>0 min</DisplayTime>
    </DpsBus>
  </Buses>
</DPS>
XML;

$xml = simplexml_load_string($xmlData);
$xml->registerXPathNamespace('r', 'http://www1.sl.se/realtidws/');
$arrLines = $xml->xpath('/r:DPS/r:Buses/r:DpsBus[r:TransportMode="BUS"]');
foreach ($arrLines as $line) {
    echo $line->LineNumber, "<br>\n";
}

Yields your desired output:

754<br>
hakre
  • 193,403
  • 52
  • 435
  • 836
kjhughes
  • 106,133
  • 27
  • 181
  • 240