Generate a JSON file from PHP

1

I'm connecting to my database, but I do not want to show the result in the template of the page but to generate a file .json .

The PHP code I use is:

<?php
$sql = "SELECT * FROM AttributeKeys WHERE atID = 1"; 

function connectDB(){

    $server = "localhost";
    $user = "user";
    $pass = "pass";
    $bd = "bd";

$conexion = mysqli_connect($server, $user, $pass,$bd);

return $conexion;
}

function disconnectDB($conexion){

$close = mysqli_close($conexion);  

return $close;
}

function getArraySQL($sql){
//Creamos la conexión con la función anterior
$conexion = connectDB();

//generamos la consulta
mysqli_set_charset($conexion, "utf8"); 

if(!$result = mysqli_query($conexion, $sql)) die(); 

$rawdata = array();

//guardamos en un array multidimensional todos los datos de la consulta
$i=0;

while($row = mysqli_fetch_array($result))
{
    $rawdata[$i] = $row;
    $i++;
}

disconnectDB($conexion); //desconectamos la base de datos

return $rawdata; //devolvemos el array
}
    $myArray = getArraySQL($sql);
    echo json_encode($myArray);
?>

How could I solve this?

    
asked by Cristian Gonzalez Herrada 06.09.2018 в 12:03
source

3 answers

2

To write the contents of the JSON in a file whose name has to do with the id of the page you can do the following at the end of your code:

<?php
$myArray = getArraySQL($sql);
// echo json_encode($myArray);
file_put_contents('js/ui0001.json', json_encode($myArray));

I have made use of the function file_put_contents() that stores in the file given in the first parameter the information provided in the second one (in this case, the array encoded in JSON).

The code assumes that the directory where you want to save the JSON files ( js ) is previously created and has permissions to write it.

    
answered by 06.09.2018 / 12:39
source
1

This should work

<?php 
$sql="select * ...."; 

$response = array();
$posts = array();
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) { 
  $title=$row['title']; 
  $url=$row['url']; 
  $posts[] = array('title'=> $title, 'url'=> $url);
} 
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
?> 

Greetings:)

    
answered by 06.09.2018 в 12:32
0

error does not give me, when I launch the page it shows me this way in my content manager:

but what I want to achieve is that the page goes blank, and generates a file in this folder:

the name of the file could be for example the id of the page ui0001.json

    
answered by 06.09.2018 в 12:31