Skip to content

Instantly share code, notes, and snippets.

@terribleplan
Last active December 25, 2015 17:59
Show Gist options
  • Save terribleplan/7017115 to your computer and use it in GitHub Desktop.
Save terribleplan/7017115 to your computer and use it in GitHub Desktop.
This /should/ parse json(p) into a nice readable format
#!/usr/bin/env php
<?php
print("\n");
//read from stdin
$rawdata = fgets(STDIN);
//pull out the callback from a jsonp request
$temp = explode('(', $rawdata, 2);
//check if the response is jsonp or not
$callback = false;
$data = '';
if (count($temp) < 2) {
//not jsonp, just try parsing the output
$data = $temp[0];
} else {
//pull out the callback
$callback = $temp[0];
//now get ready to json decode the data
$data = $temp[1];
//strip out the trailing close-paren if it exists
if (substr($data, -1) === ')') {
$data = substr($data, 0, -1);
}
}
if ($callback !== false) {
print("JSONP Callback function: " . $callback . "\n");
}
if ($data === false) {
print("No data.");
} else if ($data === '') {
print("Empty string for data.");
} else {
//parse the data into json
$obj = json_decode($data);
if ($obj === null) {
print_r($data);
print("\n\nWARNING: Invalid JSON data.");
} else {
//This is some custom stuff that will probably NOT be useful in other places
//It can be removed if it somehow causes problems
if (isset($obj->content)) {
print("\n\nParsing 'content' as important response, ignoring everything else.\n\n");
$data = trim($obj->content);
if (substr($data, 0, 4) == "&lt;") {
$data = html_entity_decode($data);
if (class_exists("tidy")) {
$tidy = tidy_parse_string($data);
if ($tidy->cleanRepair()) {
print("HTML tidy completed successfully.\n\n");
print($tidy);
} else {
print("Unable to tidy the html, sorry.\n\n");
print($data);
}
} else {
print_r($data);
print("\n\nWARNING: Tidy not installed. (--enable-tidy OR apt-get install php5-tidy).");
}
} else {
print("'content' appears to not be html, here's a full dump of the parsed json.");
print_r($obj);
}
} else {
print_r($obj);
}
print("\n\nValid json");
}
}
die("\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment