Craigslist Quick Search

Posted by Tully on Sun 12 September 2010

I wanted a quick way to search craigslist from the command line. I created a quick PHP script to do this.

The below code takes 3 arguments.

The first is the query string to search.

The second is the minimum price for the listing.

The last parameter is optional and just limits the results to whatever given integer you give it.

This script is hardcoded to the Los Angeles area, but you can change the URL to your location.

<?php
if ($argc < 3) {
    echo "Usage: php {$argv[0]} query minimumPrice [limit]n";
    exit;
}

$argv[1] = urlencode($argv[1]);

$q = “http://losangeles.craigslist.org/search/sss?query={$argv[1]}&srchType=A&minAsk={$argv[2]}}&maxAsk=&hasPic=1;

$ch = curl_init($q);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);

$dom = new DomDocument();
$dom->loadHTML($output);

$ps = $dom->getElementsByTagName(‘p’);

$count = (isset($argv[3])) ? $argv[3] : ’50′;
$i = 0

foreach ($ps as $p) {
    if ($i >= $count)
        break;

    if ($p->getAttribute(‘class’) == ‘row’) {
        echo $p->nodeValue;
    }

    $i++;
}
echo “\n”;