2013-10-13 38 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) == '') {