Adam Bell
Adam Bell

Reputation: 1045

WordPress to .json file....no data appearing

Try to convert a couple of WordPress table rows from wp_posts into a .json file. Not the JSON API plugin I've seen posted on SO many times. I've tried that and it produces too much data. I just want the ID, title and post or page content. That's it. Also, JSON API doesn't actually export a .json file. Which I want on the server dynamically.

So I'm using this script to produce the .json file.

<?php $con=mysql_connect("localhost","username","password") or die("Database connection failed");

if($con)
{
mysql_selectdb("database_wp",$con);
}
?>

<?php

$data=array();
$qa=array();
$query=mysql_query("SELECT id, title, content FROM wp_posts ORDER BY id");
while($geteach=mysql_fetch_array($query))
{
$id=$getdata[0];
$title=$getdata[1];
$content=$getdata[2];
$qa[]=array('id'=> $id, 'title'=> $title, 'content'=> $content);
}
$data['qa']=$qa;

$fp = fopen('myjson.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);

?>

But all I get in the resulting .json file is {"qa":[]} and that's it. There is data on the server. So why can't I pull it in? What's the fix?

Upvotes: 1

Views: 574

Answers (2)

RyanCameron.Me
RyanCameron.Me

Reputation: 136

Why not use the WP API plugin and use the data that way?

Upvotes: 0

Leon Hooijer
Leon Hooijer

Reputation: 584

I think the problem is in your while loop.

You use

while($geteach=mysql_fetch_array($query))
{
  $id=$getdata[0];
  $title=$getdata[1];
  $content=$getdata[2];
  $qa[]=array('id'=> $id, 'title'=> $title, 'content'=> $content);
}

I believe it should be:

while($getdata=mysql_fetch_array($query))
{
  $id=$getdata[0];
  $title=$getdata[1];
  $content=$getdata[2];
  $qa[]=array('id'=> $id, 'title'=> $title, 'content'=> $content);
}

Because otherwise $getdata is empty.

Upvotes: 1

Related Questions