2013-10-31 97 views
1

我知道這是重複的,但我不能在這一個上應用答案:LINK 我可以在不使用xmlns的情況下解析XML,但是我正在解析的feed正在使用它...Simplexml xpath和xmlns

使用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> 

非工作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>'; 
} 

這裏的任何想法? 謝謝!

+0

請定義工作。這兩個文件具有不同的XML標籤,因此它們不應該相同。你所描述的行爲看起來在技術上是正確的。 – hakre

回答

1

通過registerXPathNamespace()註冊命名空間和更新的XPath:/r:DPS/r:Buses/r:DpsBus[r:TransportMode="BUS"]

然後更新的PHP代碼:

<?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"; 
} 

息率所需輸出:

754<br> 
+0

Excellente !! :)我沒有添加ISO-8859-1編碼。 registerXPathNamespace就是這樣做的。 謝謝! – Stichy

+0

* ISO-8859-1 *沒有問題,所以我刪除了它。 – hakre