Home > Uncategorized > Output JSON from WordPress

Output JSON from WordPress

Say that you wanted to read data from a MySQL database, using PHP in a Linux environment, and then wanted to connect this data with a PhoneGap application, then you need to find a way to convert the MySQL data to JSON, to provide the interface with the PhoneGap app (which is basically HTML5)

So, as an example, I wrote a PHP script that connects to the MySQL database that underlies my OpenMerchantAccount.com blog, and converts the wp_posts table to JSON

So, I wrote the following code in PHP:

<?php
$con=mysqli_connect(“localhost”,”xxxx”,”xxxxxx”,”wordpress773″);
// Check connection
if (mysqli_connect_errno())
{
echo “Failed to connect to MySQL: ” . mysqli_connect_error();
}
mysqli_set_charset($con, “utf8″);
$result = mysqli_query($con,”SELECT * FROM wp_posts where post_status=’publish'”);
$rows = array();
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
echo json_encode($rows);
mysqli_close($con);
?>

Which is accessable via this url: http://www.presentr.info/db2json.php

Then, using a simple PhoneGap app template, I connected it to a HTML5 webpage, which is hosted here

http://www.presentr.info/demo

*Note*: You will need to use Google Chrome to visit the above url. 

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: