2

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);
4
  • Did you make sure that you get data back from the query? Commented May 22, 2013 at 23:20
  • You are calling mysql_query() twice. And the second time, when you try to get the result set, you are calling it on the result from the first $sql. Turn on error reporting and display_errors, and you'll see PHP complain about that. Commented May 22, 2013 at 23:23
  • What @MichaelBerkowski said, also you assign $url and $title to the array $row. Commented May 22, 2013 at 23:24
  • yes, the query is working fine Commented May 22, 2013 at 23:26

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I tried your code, and it returns several nulls. Like -> {"posts":[{"url":null,"title":null},...
1

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

Comments

0

Problem is in your while loop. Try this:

while($row=mysql_fetch_array($result)) { 
    $url=$row['url']; 
    $title=$row['title'];

    $posts[] = array('url'=> $url, 'title'=> $title);
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.