PHP - JSON

Converting database results into a JSON file for app building.

Query to Array

A custom function that takes a query and executes it into an array.

<?php   
    function fillArray($query){
        $array = array(); //init an array
        $query->execute();  
        while ($row = $query->fetch(PDO::FETCH_ASSOC)){
            $array[] = $row;
        }
        return $array;
    }
?>

printJSON

Call the custom function printJSON() that requires the array from fillArray() and assign a filename to download on the client's end.

<?php
    function printJSON($array,$filename){
        $json = json_encode($array);
        header('Content-disposition: attachment; filename='.$filename.'.json');
        header('Content-type: application/json');
        echo'{"'.$filename.'":'.$json.'}';
    }
?>

Calling the functions

try{
    $filename = "pets";
    $array = array(); //init an array

    $link = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $query = $link->prepare('SELECT * FROM pets');

    $array = fillArray($query);
    printJSON($array,$filename);
}
catch (PDOException $e){
    echo 'Connection failed: ' . $e->getMessage();
}