I have the following code and would like me to save the data in a array
and then display them by clicking the show button.
Does anyone know how to make a array
that stores the data entered in the first and last name variables?
<?php
//Declaro los textos que van a usar los botones de los submits
const GUARDAR = 'Guardar';
const VER_DATOS = 'Ver datos';
//Inicializo las variables que contienen los valores de los inputs a null en caso de que no se haya enviado el formulario aún
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$datos = array("nombre" => $nombre, "apellido" => $apellido);
//Si el metodo de la solicitud es un post es decir si se envio el formulario y la operacion tiene algun valor
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['operacion'])){
//Si la operacion es la de guardar.....
if($_POST['operacion'] === GUARDAR){
//Abro el archivo para escribir
$file = @fopen("datos.txt", "w");
//Creo un arreglo con los valores que voy a guardar
$data = ['nombre' => $nombre, 'apellido' => $apellido];
//Guardo el arreglo codificado a json
fwrite($file, json_encode($data));
//Cierro el archivo
fclose($file);
$nombre = null;
$apellido = null;
} else {
//Si la operacion es la de Cargar o ver y el archivo existe
if(file_exists('datos.txt')){
//Almaceno el contenido completo del archivo en esta variable
$content = file_get_contents('datos.txt');
//Decodifico el contenido almacenado en formato json
$decoded = json_decode($content);
//Asigno los valores traidos del archivo
$nombre = $decoded->nombre;
$apellido = $decoded->apellido;
}
}
}
//Cuerpo de la página
$body = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Formulario</title>
<style type="text/css">
</style>
</head>
<body bgcolor="#FFFFFF">
<FORM method="post" name="formulario" autocomplete="off">
Nombre:<input type="text" name="nombre" id="nombre" value="'.$nombre.'">
Apellido: <input type="text" name="apellido" id="apellido" value="'.$apellido.'">
<br />
<input type="submit" value="'.GUARDAR.'" name="operacion">
<input type="submit" value="'.VER_DATOS.'" name="operacion">
</FORM>
</body>
</html>';
echo $body;
echo $nombre." ".$apellido;
?>