I am using jwilsson's spotify-web-api-php to return data from the Spotify API using PHP.
Also I'm using digitalnature's php-ref to return info about variables.
This is my (terrible) code:
// https://stackoverflow.com/questions/4345554/convert-a-php-object-to-an-associative-array
function objectToArray($r)
{
if (is_object($r)) {
if (method_exists($r, 'toArray')) {
return $r->toArray(); // returns result directly
} else {
$r = get_object_vars($r);
}
}
if (is_array($r)) {
$r = array_map(__FUNCTION__, $r); // recursive function call
}
return $r;
}
$session = new SpotifyWebAPI\Session(
'aaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbb'
);
$session->requestCredentialsToken();
$accessToken = $session->getAccessToken();
$str = $_POST['str'];
$str_length = strlen($_POST['str']);
$html = null;
$api = new SpotifyWebAPI\SpotifyWebAPI();
$api->setAccessToken($accessToken);
$search = $api->search('fugazi','artist');
$search_array = objectToArray($search);
r($search_array);
// loop through the results
foreach($search_array['artists']['items'] as $item) {
// artist name
$artist_name = $item['name'];
$html .= "<h2>$artist_name</h2>";
// genres
foreach($item['genres'] as $genre) {
$html .= " <span class='code'>$genre</span> ";
}
// $v2 = $item['images']['0']['height'];
// r($v2);
}
This is what the php-ref shows the $search_array
to look like:
Or as plain text: https://0bin.net/paste/iPYfn2M6#Pt8l-a9i9el0TVnZsDTA8wlbe/t0CGSIsp4bds0IZyT
I would like to access the attributes for the first element in the images array for each artist returned.
I tried via this line:
$v2 = $item['images']['0']['height'];
But the following error was returned:
PHP Notice: Undefined offset: 0 in C:\Websites\spotify\search.php on line 68
PHP Notice: Trying to access array offset on value of type null in C:\Websites\spotify\search.php on line 68
I have searched around that error but I can't get my head around the correct syntax to use in this example.
Sorry for my lack of understanding.