Skip to content

Instantly share code, notes, and snippets.

@syranez
Created September 11, 2011 14:58
Show Gist options
  • Save syranez/1209683 to your computer and use it in GitHub Desktop.
Save syranez/1209683 to your computer and use it in GitHub Desktop.
Konvertiert scores.txt von christoph-d in ein JSON-Objekt.
<?php
namespace CrawlChristophdDe;
/**
* konvertiert die Highscoreliste von Dungeon Crawl bei Christoph in
* ein JSON-Objekt
*
* Verwendung:
*
* $converter = CrawlChristophdDe\ApiToJson();
* $json = $converter->convert();
*
*/
final class ApiToJSON {
/**
* URI zu Scores-API von Christoph-d
*
* @var string
*/
const URI = 'http://crawl.christoph-d.de/scores.txt';
/**
* __construct
*
*/
public function __construct () {
}
/**
* konvertiert die Highscore-Liste nach JSON.
*
* @return array JSON-formatiert
*/
public function convert () {
$content = $this->getFile(self::URI);
$scores = $this->parse($content);
return json_encode($scores);
}
/**
* lädt die Datei und parst diese in ein Array
*
* @param string $file scores.txt
*/
private function getFile ($file) {
$content = file_get_contents($file);
$foo = explode('v=0.9-b1:', $content);
$bar = array();
foreach ($foo as $key => $value) {
if (strlen($value)) {
$bar[$key] = explode(':', $value);
}
}
return $bar;
}
/**
* parst die scores.txt-"API" ;) in ein mehrdimensionales Array
*
* @param array $content scores.txt
* @return array
*/
private function parse ($content) {
$scores = array();
foreach ($content as $number => $line) {
$entry = array();
foreach ($line as $k => $v) {
if (stristr($v, '=')) {
$row = array();
$row = $this->encode(explode('=', $v));
$entry[$row[0]] = $row[1];
}
}
$scores[$number] = $entry;
}
return $scores;
}
private function encode (array $row) {
$encoded = array();
$length = count($row);
for ($i = 0; $i < $length; $i += 1) {
$encoded[$i] = htmlspecialchars(trim($row[$i]));
$encoded[$i] = strip_tags($encoded[$i]);
// Spezialzeichen entfernen
$encoded[$i] = strtr($encoded[$i], array("\n" => " ", "\r" => " ", " " => " "));
}
return $encoded;
}
}
$jsonConverter = new ApiToJson();
echo $jsonConverter->convert();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment