Reading remote file contents with PHP+CURL
The preferred method to read contents of a file into a string with PHP is usually file_get_contents(), but sometimes server configurations do not allow for file_get_contents() to read from a remote server. Luckily CURL provides a nice workaround (you must have the libcurl package installed on your version of PHP). Here's how I retrieve data from my anime list on AniDB.net for use on anime.zakness.com:
The function: get_contents()
- // returns a String containing the contents of a URL
- function get_contents($url, $post="") {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
- if (!empty($post)) {
- curl_setopt($ch, CURLOPT_POST,1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
- }
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_ENCODING, "");
- $string = curl_exec($ch) or die(curl_error());
- curl_close($ch);
- return $string;
- }
- source file: get-contents.txt
Using get_contents() to access anidb.net
I can use get_contents() to access the source code of my AniDB MyList (which needs to send POST information to AniDB's server). Then I use preg_match_all() to get all the relevant information and populate the data array ($data).
- $data = array();
- $errors = array();
- $source = get_contents("http://anidb.info/perl-bin/animedb.pl", "show=mylist&xuser=zaclin&xpass=******");
- if (empty($source)) array_push($errors, "Could not retrieve raw source data.");
- preg_match_all("@class=\"title\".+aid=(\d+)\">(.+)<\/a>.+(\d+?)\s*\/\s*(\d+?).+(\d+?)\s*\/\s*\d+@Usx", $source, $m, PREG_SET_ORDER);
- if (!$m) array_push($errors,"Could not find matching data.");
- else {
- foreach ($m as $match) {
- $d = array();
- $d['id'] = $match[1];
- $d['name'] = $match[2];
- $d['have'] = $match[3];
- $d['total'] = $match[4];
- $d['seen'] = $match[5];
- $data[] = $d;
- }
- }
- source file: get-contents-example.txt
These two snippets do all the dirty work for me, now I can do whatever I want with the data. Not too shabby!