如果XML元素不存在,则通过PHP回显消息

时间:2012-05-21 08:50:34

标签: php xml api xpath last.fm

经过对该主题的一些实质性研究后,遗憾的是我找不到答案。我想这里对很多人来说这是一个非常简单的问题。

我通过他们的API(使用PHP)连接到Last.fm的XML数据库。在输入存在的艺术家或空白字段时,我可以回答正确的信息而没有任何问题。但是,如果用户输入不存在的艺术家,我无法回应任何内容。

我的问题是这个;如果该XML元素不存在,我该如何回显我想要的任何消息?我的思路如下:

   foreach ($uk_events as $event){

$venue_city = (string) $event->venue->location->city;
$image = (string) $event->image[2];
$uk_street = (string) $event->venue->location->street;
$uk_postcode = (string) $event->venue->location->postalcode;
$startdate = (string) $event->startDate;
$starttime = (string) $event->startTime;
$uk_venues = (string) $event->venue->name; 
$uk_names = (string) $event->artists->artist;
$website = (string) $event->website;

        if (empty($uk_names)){

    echo "<p class='sorry'>Sorry, but it doesn't look like this artist exists. Either they're exceptionally obscure or they're from
    another realm. Try again, or have a look at the below suggestions.</p>";

    }

经过一些试验和错误之后,我得到的最好的结果就是回应了上述情况,但无论搜索到什么,它都会得到回应。 只有在XML数据库中不存在艺术家时才需要出现上述内容。

非常感谢任何能够让我了解如何在这个方面取得进展的人。

谢谢。

1 个答案:

答案 0 :(得分:0)

如果您正在使用GitHub中的SDK进行调用

$uk_events = $artistClass->search($methodVars)

然后您可以编辑您的代码以阅读

if ($uk_events === false) {
    echo "<p class='sorry'>Sorry, we couldn't contact the server. Try again later.</p>";             

} elseif (empty($uk_events)) {
    echo "<p class='sorry'>Sorry, but it doesn't look like this artist exists. Either they're exceptionally obscure or they're from another realm. Try again, or have a look at the below suggestions.</p>";             

} else {
   foreach ($uk_events as $event){             
       .... // print list
   }      
} 

如果您正在使用原始API调用,则会收到类似

的响应
// Response to http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=NotARealArtist

<?xml version="1.0" encoding="UTF-8"?>
<lfm status="ok">
  <results xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" for="NotARealArtist">
    <opensearch:Query role="request" startPage="1" searchTerms="NotARealArtist"/>
    <opensearch:totalResults>0</opensearch:totalResults>
    <opensearch:startIndex>0</opensearch:startIndex>
    <opensearch:itemsPerPage>30</opensearch:itemsPerPage>
    <artistmatches>
    </artistmatches>
  </results>
</lfm>

所以,你有两种方法可以确定你没有艺术家:

  1. “opensearch:totalResults”元素包含值“0”
  2. “artistmatches”中的子元素数量为零
  3. 因此解析这些值的XML。