0) { sleep($delay); } # read file if (!file_exists($BOOKS_FILE)) { header("HTTP/1.1 500 Server Error"); die("ERROR 500: Server error - Unable to read input file: $BOOKS_FILE"); } header("Content-type: application/json"); # this code was written in the pre- json_encode days; alas if ($category) { print "{\n \"books\": [\n"; $lines = file($BOOKS_FILE); # count matches (to avoid trailing comma later) $matches = 0; for ($i = 0; $i < count($lines); $i++) { list($title, $author, $book_category, $year, $price) = explode("|", trim($lines[$i])); if ($book_category == $category) { $matches++; } } $matches_found = 0; for ($i = 0; $i < count($lines); $i++) { # Bachelor Chow in 20 Minutes|Gloria Demartelaere|cooking|2005|30.00 list($title, $author, $book_category, $year, $price) = explode("|", trim($lines[$i])); if ($book_category == $category) { # print it as XML print " {\"category\": \"$category\", \"year\": $year, \"price\": $price, \n \"title\": \"$title\", \"author\": \"$author\"}"; if ($matches_found < $matches - 1) { print ","; } $matches_found++; print "\n"; } } print " ]\n}\n"; } else { print "{\n"; print "\t\"categories\": [\n"; $categories = array(); $count = 0; foreach (file($BOOKS_FILE) as $line) { list($title, $author, $book_category, $year, $price) = explode("|", trim($line)); if (!isset($categories[$book_category])) { $categories[$book_category] = 1; $count++; } } ksort($categories); foreach ($categories as $book_category => $useless) { $count--; print "\t\t\"$book_category\""; if ($count > 0) { print ","; } print "\n"; } print "\t]\n"; print "}\n"; } ?>