Generate .json file with PHP MySQL

11,864

Solution 1

There are many mistakes in your code! Please check this:

$result=mysql_query("SELECT * FROM wp_posts");

$i=0;
while($row=mysql_fetch_array($result)) { 
$response[$i]['url']  = $row['url']; 
$response[$i]['title']= $row['title'];
$data['posts'][$i] = $response[$i];
$i=$i+1;
} 

$json_string = json_encode($data);

$file = 'file.json';
file_put_contents($file, $json_string);

Solution 2

Try this

header('Content-Type: application/json');    
$sql=mysql_query("SELECT * FROM wp_posts"); 
$response = array();
$posts = array();
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) 
{ 
  $posts['url']=$row['url'];; 
  $posts['title']=$row['title'];
  array_push($response, $posts);
} 
$json = json_encode($response);
$file = 'file.json';
file_put_contents($file, $json);

Reference: visit here

Share:
11,864
qebas
Author by

qebas

Updated on July 18, 2022

Comments

  • qebas
    qebas almost 2 years

    I'm trying to generate a json file with PHP with the code below and I'm getting an empty array -> {"posts":[]}. I'm using Wordpress. Can someone assist me. Thanks

        $sql=mysql_query("SELECT * FROM wp_posts"); 
    
        $response = array();
        $posts = array();
        $result=mysql_query($sql);
        while($row=mysql_fetch_array($result)) 
        { 
        $url['url']=$row; 
        $title['title']=$row;
    
        $posts[] = array('url'=> $url, 'title'=> $title);
    
        } 
    
        $response['posts'] = $posts;
    
        $fp = fopen('results.json', 'w');
        fwrite($fp, json_encode($response));
        fclose($fp);
    
  • qebas
    qebas almost 11 years
    I tried your code, and it returns several nulls. Like -> {"posts":[{"url":null,"title":null},...