2013-05-07 70 views
1

我正在製作一個簡單的基於Web的應用程序,顯示到達我家附近地鐵站的列車到達時間(以分鐘爲單位)。從REST API的XML輸出中的特定鍵值獲取價值

地鐵(華盛頓地鐵)發佈了一個API,它使開發人員能夠訪問這些信息:當我使用的示例代碼從上面的鏈接我得到這樣的標記文本列表http://developer.wmata.com/docs/read/GetRailStationInfo

<AIMPredictionResp xmlns="http://www.wmata.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
<Trains> 
<AIMPredictionTrainInfo> 
<Car>6</Car> 
<Destination>NewCrltn</Destination> 
<DestinationCode>D13</DestinationCode> 
<DestinationName>New Carrollton</DestinationName> 
<Group>1</Group> 
<Line>OR</Line> 
<LocationCode>K03</LocationCode> 
<LocationName>Virginia Square</LocationName> 
<Min>7</Min> 
</AIMPredictionTrainInfo> 
</Trains> 

所有我想要顯示的是分鐘包裹在<閩> </MIN>標籤。什麼是最好的方式去做這件事?是否有一個我可以編寫的PHP腳本可以提取這個數字?如果是這樣,請你指點我正確的方向?

謝謝!

更新:

非常感謝大家。我已經嘗試了您發送的教程中的一個示例,但是當我在其中切換我的URL(使用鍵)時,它不顯示任何內容。

<?php 
$trainInfo = simplexml_load_file("api.wmata.com/StationPrediction.svc/GetPrediction/_KEYXXXXXXXX); 

print $trainInfo->AIMPredictionTrainInfo->LocationName; 
print $trainInfo->AIMPredictionTrainInfo->Min; 

?> 
+1

要麼提供的答案會工作。我建議在這種情況下使用SimpleXML。 – gview 2013-05-08 00:17:40

回答

1

要在被拉出的方向是SimpleXML

例(未測試):

<?php 
$xml = new SimpleXMLElement($my_input_xml); 

echo $xml->getMin() . "<br>"; 

?> 

下面是其他一些很好的教程:

「希望幫助!

+0

'E_ERROR:type 1 - 調用未定義的方法SimpleXMLElement :: getMin() - 在行......'這真的離開了一個工作示例! – hek2mgl 2013-05-08 00:35:45

+0

這確實有幫助。謝謝。 我已經嘗試了您發送的教程中的一個示例,但是當我切換我的URL(使用鍵)時,它不顯示任何內容。 AIMPredictionTrainInfo-> LOCATIONNAME; 打印$ trainInfo-> AIMPredictionTrainInfo->敏; ?> – user1650020 2013-05-08 00:45:55

1

這裏是一個使用DOMXPath(測試)的例子。重要的是註冊的默認命名空間:

$data = <<<EOF 
<?xml version="1.0"?> 
<AIMPredictionResp xmlns="http://www.wmata.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
<Trains> 
<AIMPredictionTrainInfo> 
<Car>6</Car> 
<Destination>NewCrltn</Destination> 
<DestinationCode>D13</DestinationCode> 
<DestinationName>New Carrollton</DestinationName> 
<Group>1</Group> 
<Line>OR</Line> 
<LocationCode>K03</LocationCode> 
<LocationName>Virginia Square</LocationName> 
<Min>7</Min> 
</AIMPredictionTrainInfo> 
</Trains> 
</AIMPredictionResp> 
EOF; 

$doc = new DOMDocument(); 
$doc->loadXML($data); 

$selector = new DOMXPath($doc); 
$selector->registerNamespace(
    'default', 
    'http://www.wmata.com' 
); 

$query = '//default:Min'; 
foreach($selector->query($query) as $node) { 
    var_dump($node->nodeValue); 
} 

輸出:

string(1) "7"