Suren Suren - 4 months ago 8
JSON Question

Decode php encoded json not working

Here is my data.php

$global = $pdo->query("SELECT name, age");
$global = $global->fetchAll(PDO::FETCH_ASSOC);
$arr = array('data'=>$global);
echo json_encode($arr, JSON_PRETTY_PRINT);


Here is my index.php

<html>
<?php
$json_url = "data.php";
$json = utf8_encode(file_get_contents($json_url));
$data = json_decode($json, false);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
</html>


I get blank data. What am I doing wrong?

Answer

Try this:

$query = "SELECT * FROM table";
$stmt = $pdo->query($query);
$global= $stmt->fetchAll(PDO::FETCH_ASSOC);
$arr = array('data'=>$global);    
echo json_encode($arr);
//echo json_encode($arr, JSON_PRETTY_PRINT);