2016-09-04 95 views
1

我有一個相當簡單的一塊PHP代碼,只有繼續讀取XML,如果變量具有一定的價值

$xml = file_get_contents($url, false, $context); 
$response = simplexml_load_string($xml); 
$status_response = $response->xpath('/PollSessionResponseDto/Status'); 
$answer = $status_response[0]; 

while ($answer<>"UpdatesComplete") { 
    sleep(2); 
    $answer = $response->xpath('/PollSessionResponseDto/Status')[0]; 
} 

$itenaries = $response->xpath('/PollSessionResponseDto/Itineraries/ItineraryApiDto'); 

reading an XML file, for example,我只希望繼續閱讀itenaries如果XML文件中的地位「UpdatesComplete」。如果狀態是「UpdatesPending」,我基本上想等待2秒。然後再次檢查,如果需要再等2秒。

但是我最終陷入了無限循環。我檢查了我的$answer變量,看來我得到了我想檢查的字符串(UpdatesPending或UpdatesComplete)。

有人可以告訴我我做錯了什麼嗎?

回答

1

$answer的值將從不在您的循環內部發生更改,因爲您永遠不會從遠程主機重新加載XML文件。

do { 

    $xml = file_get_contents($url, false, $context); 
    $response = simplexml_load_string($xml); 

    $answer = $response->xpath('/PollSessionResponseDto/Status')[0]; 

} while ($answer != "UpdatesComplete" && slee(2)); 
+0

謝謝謝里夫,總是有道理。但是,我現在正在收到一條錯誤消息致命錯誤:未捕獲錯誤:調用線上的布爾值成員函數xpath()$ answer = $ response-> xpath('/ PollSessionResponseDto/Status')[0]; 你知道爲什麼嗎? –

+1

由於['simplexml_load_string'](http://php.net/simplexml-load-string)在失敗時返回'false',這意味着'simplexml_load_string'失敗。 – Sherif

+0

謝謝,就是這樣。 –