0

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

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

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

谢谢你。

4

1 回答 1

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”中的子元素数量为零

所以解析这些值的 XML。

于 2012-05-21T11:35:56.200 回答