2013-10-13 34 views
1

在PHP腳本,我從一個XML文件上的外部網站調試獲取的兩個屬性的一個關鍵功能。這些屬性在名爲Channel的標籤內標記爲'code'和'locationCode'。問題是,有時locationCode過帳爲空字符串(「」)或不是由網站渠道我不能使用定義的好,所以我需要通過渠道循環,直到我找到一個非空locationCode字符串。爲此,我創建了一個while循環,但是我當前的實現沒有成功地通過位置代碼循環。有沒有更好的方法來實現這一點?檢查空屬性在解析XML文件

當前代碼:代碼

public function setChannelAndLocation(){ 
    $channelUrl="http://service.iris.edu/fdsnws/station/1/query?net=".$this->nearestNetworkCode. 
    "&sta=".$this->nearestStationCode."&starttime=2013-06-07T01:00:00&endtime=".$this->impulseDate. 
    "&level=channel&format=xml&nodata=404"; 
    $channelXml= file_get_contents($channelUrl); 
    $channel_table = new SimpleXMLElement($channelXml); 

    $this->channelUrlTest=$channelUrl; 
    //FIXME: Check for empty locationCode string 
    $this->channelCode = $channel_table->Network->Station->Channel[0]['code']; 
    $this->locationCode = $channel_table->Network->Station->Channel[0]['locationCode']; 
    $i = 1; 
    while($this->locationCode=''){ 
    $this->channelCode = $channel_table->Network->Station->Channel[$i]['code']; 
    $this->locationCode = $channel_table->Network->Station->Channel[$i]['locationCode']; 
    $i++; 
    } 
} 

示例XML文件:http://service.iris.edu/fdsnws/station/1/query?net=PS&sta=BAG&starttime=2013-06-07T01:00:00&endtime=2013-10-12T18:47:09.5000&level=channel&format=xml&nodata=404

+1

['$ locationCode = $ channel_table->的XPath( '//通道/ @ locationCode [= 「」。!]');'(http://php.net/manual/en/simplexmlelement.xpath.php) – Wrikken

+0

或實際, namspaces在那裏,所以['$ channel_table-> - > registerXPathNamespace( '默認',的 'http://www.fdsn.org/xml/station/1'); $ locationCode = $ channel_table->的xpath('//默認:Channel/@ locationCode [。!=「」]');'](http://php.net/manual/en/simplexmlelement.xpath.php) – Wrikken

回答

1

有兩個問題,我可以用這條線看:

while($this->locationCode=''){ 

首先,您鍵入的轉讓(=)當你想要的是一個比較(==)。因此,而不是測試條件下,這條線是在寫作的$this->locationCode當前值,然後測試的''「感實性」,其計算結果爲false,所以while循環永遠不會運行。

其次,示例XML文件顯示屬性其實也不是空的,但包含了一些空白。假設這些都是要忽略的值(有沒有在樣品中,現在具有任何其他值),可以使用trim()以消除比較空白,給你這個:

while(trim($this->locationCode) == '') {