这是我完整的脚本。我想做的是将$bg设置为如果URL的响应为"null",则设为"none.jpg"。如果响应是其他东西,设置$bg,就像我在这个脚本中已经做的那样。
$backgroundURL = 'http://api.fanart.tv/webservice/artist/a93e666f14a34d979b3e3617eab2f340/6b1cf581-17a9-42c3-927b-d1e2797b1695/json/artistbackground/1/1';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $backgroundURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; curl)");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$json = curl_exec($ch);
curl_close($ch);
$json = json_decode($json);
$first = current($json);
$bg = $first->artistbackground[0]->url;
这就是你要找的:
if('null'==$json){
echo 'Nothing here!';
} else {
echo 'Yep, found it!';
}
如果结果确实包含文字字符串 "null",那么您必须比较该字符串,而不是与语言结构NULL
进行比较。
考虑到你下面的评论,我测试了你的脚本,并添加了一个如上所述的条件。
<?php
$backgroundURL = 'http://api.fanart.tv/webservice/artist/a93e666f14a34d979b3e3617eab2f340/6b1cf581-17a9-42c3-927b-d1e2797b1695/json/artistbackground/1/1';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $backgroundURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; curl)");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$json = curl_exec($ch);
curl_close($ch);
if ('null'==$json) {
echo "reply is 'null''n";
} else {
echo "reply is NOT 'null''n";
}
?>
输出如预期:reply is 'null'
…