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


Echo message via PHP if XML element doesn't exist

在对这个话题进行了一些实质性的研究之后,不幸的是,我没有找到答案。我想,对于这里的很多人来说,这是一个非常简单的问题。

我通过他们的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 数据库中不存在时,我才需要显示上述内容。

非常感谢任何能给我一个关于如何在这个方面取得进展的想法的人。

谢谢。

如果你在调用中使用 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. "艺术家匹配"中的子元素数为零

因此,请解析这些值的 XML。