Reply To: CS108 Post to Web Example

#8937 Reply

RTLSLab

<?php

//Make sure that it is a POST request.
if(strcasecmp($_SERVER[‘REQUEST_METHOD’], ‘POST’) != 0){
throw new Exception(‘Request method must be POST!’);
}

//Receive the RAW post data.
$content = trim(file_get_contents(“php://input”));

//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);

//If json_decode failed, the JSON is invalid.
if(!is_array($decoded)){
throw new Exception(‘Received content contained invalid JSON!’);
}

//Process the JSON.

function array2table($array, $recursive = false, $null = ‘ ‘)
{
// Sanity check
if (empty($array) || !is_array($array)) {
return false;
}

if (!isset($array[0]) || !is_array($array[0])) {
$array = array($array);
}

// Start the table
$table = “<table border=1 style=’text-align: center;
vertical-align: middle;’>\n”;

// The header
$table .= “\t<tr>”;
// Take the keys from the first row as the headings
foreach (array_keys($array[0]) as $heading) {
$table .= ‘<th>’ . $heading . ‘</th>’;
}
$table .= “</tr>\n”;

// The body
foreach ($array as $row) {
$table .= “\t<tr>” ;
foreach ($row as $cell) {
$table .= ‘<td>’;

// Cast objects
if (is_object($cell)) { $cell = (array) $cell; }

if ($recursive === true && is_array($cell) && !empty($cell)) {
// Recursive mode
$table .= “\n” . array2table($cell, true, ‘null’) . “\n”;
} else {
$table .= (strlen($cell) > 0) ?
htmlspecialchars((string) $cell) :
$null;
}

$table .= ‘</td>’;
}

$table .= “</tr>\n”;
}

$table .= ‘</table>’;
return $table;
}

$file = ‘output.html’;

file_put_contents($file, array2table($decoded, true, ‘null’), FILE_APPEND | LOCK_EX);

?>