在分析 XML 文件时检查空属性


Checking for empty attributes while parsing an XML file

PHP 脚本中的一个关键函数 我正在调试外部站点上的 XML 文件中获取的两个属性。这些属性在名为"渠道"的标记中标记为"代码"和"位置代码"。问题是有时 locationCode 被发布为空字符串 ('') 或站点根本没有为我无法使用的频道定义,所以我需要遍历通道,直到找到一个非空的 locationCode 字符串。为此,我创建了一个 while 循环,但我当前的实现无法成功循环访问位置代码。有没有更好的方法来实现这一点?

当前代码:

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

我可以看到这一行有两个问题:

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

首先,你输入了一个作业(=),而你想要的是一个比较(==)。因此,这条线不是测试条件,而是覆盖$this->locationCode的当前值,然后测试''的"真实性",其计算结果为false,因此while循环永远不会运行。

其次,示例 XML 文件显示该属性实际上并不为空,而是包含一些空格。假设这些是您要忽略的值(现在示例中没有具有任何其他值的值),您可以使用trim()从比较中删除空格,从而得到以下内容:

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