Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
<?php
// Archivo donde se guardarán los datos
$jsonFile = 'datos.json';
// Procesar el formulario cuando se envía
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Recoger datos del formulario
$nombre = $_POST['nombre'] ?? '';
$edad = $_POST['edad'] ?? '';
$email = $_POST['email'] ?? '';
$ciudad = $_POST['ciudad'] ?? ''; // Nota: Hay un error tipográfico en el name del formulario (ciudad vs ciudad)
// Validar datos básicos
if (!empty($nombre) && !empty($edad)) {
// Crear array con los datos
$nuevoDato = [
'nombre' => $nombre,
'edad' => (int)$edad,
'email' => $email,
'ciudad' => $ciudad,
'fecha_registro' => date('Y-m-d H:i:s')
];
// Leer datos existentes
$datosExistentes = [];
if (file_exists($jsonFile)) {
$contenido = file_get_contents($jsonFile);
$datosExistentes = json_decode($contenido, true) ?: [];
}
// Agregar nuevo dato
$datosExistentes[] = $nuevoDato;
// Guardar en archivo JSON
file_put_contents($jsonFile, json_encode($datosExistentes, JSON_PRETTY_PRINT));
// Mensaje de éxito
$mensaje = "Datos guardados correctamente!";
} else {
$error = "Nombre y edad son campos obligatorios!";
}
}
// Leer datos existentes para mostrar
$datosMostrar = [];
if (file_exists($jsonFile)) {
$contenido = file_get_contents($jsonFile);
$datosMostrar = json_decode($contenido, true) ?: [];
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Formulario JSON</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
.formulario { background: #f5f5f5; padding: 20px; border-radius: 8px; margin-bottom: 30px; }
.datos { background: #e9f7ef; padding: 20px; border-radius: 8px; }
.success { color: green; }
.error { color: red; }
input, button { padding: 8px; margin: 5px 0; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>Formulario y Consumo de JSON</h1>
<!-- Sección superior: Formulario para crear JSON -->
<div class="formulario">
<h2>Ingresar Datos</h2>
<?php if (isset($mensaje)): ?>
<p class="success"><?php echo htmlspecialchars($mensaje); ?></p>
<?php endif; ?>
<?php if (isset($error)): ?>
<p class="error"><?php echo htmlspecialchars($error); ?></p>
<?php endif; ?>
<form method="post">
<div>
<label for="nombre">Nombre:</label>
<input type="text" id="nombre" name="nombre" required>
</div>
<div>
<label for="edad">Edad:</label>
<input type="number" id="edad" name="edad" required>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
</div>
<div>
<label for="ciudad">Ciudad:</label>
<input type="text" id="ciudad" name="ciudad">
</div>
<button type="submit">Guardar Datos</button>
</form>
</div>
<!-- Sección inferior: Consumir y mostrar datos del JSON -->
<div class="datos">
<h2>Datos Almacenados</h2>
<?php if (empty($datosMostrar)): ?>
<p>No hay datos almacenados aún.</p>
<?php else: ?>
<table>
<thead>
<tr>
<th>Nombre</th>
<th>Edad</th>
<th>Email</th>
<th>Ciudad</th>
<th>Fecha Registro</th>
</tr>
</thead>
<tbody>
<?php foreach ($datosMostrar as $dato): ?>
<tr>
<td><?php echo htmlspecialchars($dato['nombre']); ?></td>
<td><?php echo htmlspecialchars($dato['edad']); ?></td>
<td><?php echo htmlspecialchars($dato['email'] ?? 'N/A'); ?></td>
<td><?php echo htmlspecialchars($dato['ciudad'] ?? 'N/A'); ?></td>
<td><?php echo htmlspecialchars($dato['fecha_registro']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<h3>JSON Completo:</h3>
<pre><?php echo htmlspecialchars(json_encode($datosMostrar, JSON_PRETTY_PRINT)); ?></pre>
<?php endif; ?>
</div>
</body>
</html>