Archive for the ‘PHP’ Category

Sorting muilti-dimensional arrays in PHP

I ALWAYS forget this so I am posting it for myself and anyone else who stumbles upon it.

function subval_sort($a,$subkey) {
 foreach($a as $k=>$v) {
 $b[$k] = strtolower($v[$subkey]);
 foreach($b as $key=>$val) {
 $c[] = $a[$key];
 return $c;
$songs = subval_sort($songs,'artist'); 
 [0] => Array
 [artist] => Fleetwood Mac
 [song] => Second-hand News

 [1] => Array
 [artist] => The Decemberists
 [song] => The Island

 [2] => Array
 [artist] => The Smashing Pumpkins
 [song] => Cherub Rock


Taken from this site:


Accessing the Discogs API v2 with PHP

To save someone a little time, here are two ways I was able to successfully send requests and get a 200 response. I was getting 406 because I was relying on my server sending HTTP_ACCEPT_ENCODING, which is apparently not enough.

Using cUrl:

// create curl resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, "");

//send headers
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Accept-Encoding: gzip', 'User-Agent: ExampleBot/1.0'));

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources

echo $output;

Using PHP get_file_contents (Thanks vreon at Discogs):

$ctx_options = array('http' => array('method' => 'GET', 'header' => 'Accept-Encoding: gzip, deflate\r\nUser-Agent: ExampleBot/1.0\r\n'));
$ctx = stream_context_create($ctx_options);
echo file_get_contents('', false, $ctx);

Of course, make a up a unique user agent.