- Forums
- Scripts
- PHP/JSON - Render JSON Object With PHP Mysql Database File To The Browser API
use this snippet to generate JSON object data from a php file [5000], Last Updated: Mon Jun 24, 2024
edwin
Sat Jul 23, 2022
0 Comments
1148 Visits
JSON using PHP File
Use this snippet to generate JSON object data from a php file.
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include_once '../dbconnect.php';
$dataArr = array();
$sql = "SELECT * FROM scripts";
if ($result = $mysqli->query($sql)) {
while ($scripts = $result->fetch_object()) {
//echo '<PRE>LINE '.__LINE__.' - ';print_r($scripts);echo '</pre>';
array_push($dataArr,$scripts);
}
}
$dataObj = (object) ['results' => $dataArr];
echo json_encode($dataObj);
?>
The code above will render something like this in the browser:
{
"results": [
{
"id": "1",
"secret": "xydasdw3233z",
"name": "Contactus",
"path": "https://localhost/scrip1"
},
{
"id": "2",
"secret": "ang23423e32fdss",
"name": "Angular Quiz",
"path": "https://localhost/scrip12"
}
]
}