Question

This is my complete script. What I want to do is to set $bg to let's say "none.jpg" if the response from the URL is "null". If the response is something else, set $bg as I'm already doing in this script.

$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;
Was it helpful?

Solution

This is what you are looking for:

if('null'==$json){
  echo 'Nothing here!';   
} else {
  echo 'Yep, found it!';
}

If the result really contains the literal string "null" as you state, then you must compare that that string, not to the language construct NULL.


Considering your comments below I tested your script and added a conditional as written above.

<?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";
}
?>

The output is as expected: reply is 'null'...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top