Files
2026-03-05 14:00:26 +01:00

90 lines
2.9 KiB
PHP
Executable File

<?php
class JsonToHtmlParser {
public function parseJsonFile($jsonFilePath) {
echo "Current working dir: " . getcwd() . "\n";
echo "Checking file at: $jsonFilePath\n";
$resolvedPath = realpath($jsonFilePath);
echo "Resolved file path: $resolvedPath\n";
if (!file_exists($resolvedPath)) {
die("JSON file not found at $resolvedPath\n");
}
echo "File found!\n";
$jsonData = json_decode(file_get_contents($resolvedPath), true);
if ($jsonData === null) {
die("Failed to decode JSON: " . json_last_error_msg());
}
return $this->buildHtml($jsonData);
}
private function buildHtml($data) {
$html = "<!DOCTYPE html>\n<html>\n";
if (isset($data['head'])) {
$html .= $this->parseHead($data['head']);
}
if (isset($data['body'])) {
$html .= "<body>\n" . $this->parseContent($data['body']['content']) . "\n</body>\n";
}
$html .= "</html>";
return $html;
}
private function parseHead($headData) {
$html = "<head>\n";
// Title
if (isset($headData['title'])) {
$html .= "<title>{$headData['title']}</title>\n";
}
// Inline CSS Styles
if (isset($headData['styles'])) {
$html .= "<style>\n{$headData['styles']}\n</style>\n";
}
$html .= "</head>\n";
return $html;
}
private function parseContent($contentArray) {
$html = "";
foreach ($contentArray as $element) {
$html .= $this->createElement($element);
}
return $html;
}
private function createElement($element) {
if (!isset($element['element'])) return "";
$tag = $element['element'];
$attributes = isset($element['attributes']) ? $this->parseAttributes($element['attributes']) : "";
$value = isset($element['value']) ? $element['value'] : "";
$innerHtml = isset($element['content']) ? $this->parseContent($element['content']) : "";
return "<$tag $attributes>$value$innerHtml</$tag>\n";
}
private function parseAttributes($attributes) {
$htmlAttributes = "";
foreach ($attributes as $key => $value) {
$htmlAttributes .= "$key=\"$value\" ";
}
return trim($htmlAttributes);
}
}
// Instantiate and use the class outside the class definition
$parser = new JsonToHtmlParser();
$htmlOutput = $parser->parseJsonFile("/home/ortelbachf/Schreibtisch/Examplary/Simple.json");
// Automatically save the HTML to output.html in the same directory
$outputFilePath = getcwd() . "/output2.html";
file_put_contents($outputFilePath, $htmlOutput);
echo "HTML file generated successfully! Open 'output.html' to view the website.";
?>