« Return

Retrieve and parse delicious bookmarks


PHP
<?php
function get_delicious() {

  $cache = 'delicious.xml';
  
  // fetch updated content if necessary
  /* ========================================================================================== */
  if (filemtime($cache) < (time() - 10800)) :

      $url = 'https://username:password@api.del.icio.us/v1/posts/recent?count=15';
      $curl = curl_init($url);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($curl, CURLOPT_TIMEOUT, 5);
      $data = curl_exec($curl);
      curl_close($curl);

      // write only if cURL returns string. if fails, returns bool(false)
      if (is_string($data)) { $handle = fopen($cache, 'w'); fwrite($handle, $data); fclose($handle); }
      else { $data = file_get_contents($cache); }

  // if the xml cached file was not expired, read
  /* ========================================================================================== */    
  else: $data = file_get_contents($cache);
  endif;

  // now that we have the $data string. parse the xml and format the html
  /* ========================================================================================== */    
  $xml = simplexml_load_string($data);

  if (!$xml) { echo "Failed loading XML" . "\n"; }
  else {
  $html = '<ul>';
  foreach($xml as $item) { $html .= '<li><a href="' . $item['href'] . '">' . $item['description'] . '</a></li>'; }  
  $html .= '</ul>';
  }    
  
  return $html;
  
} // end get_delicious
?>