Getting JSON returns from Restful API via WordPress HTTP API and parsing them.

WordPress 4.0 is coming out soon, one of the highlights is the addition of Restful API, today we advance to see how to get Restful API JSON content and display it. The process is to use PHP to get the content of the remote JSON, and then convert the JSON into PHP objects, and then output the content in a loop. This is accomplished by using PHP and the WordPress HTTP API can be realized in both ways, let's take a look at the code that implements both ways.

PHP fopen method

$handle = fopen("http://yoursite.com/news", "rb");

$content = "";

while (!feof($handle)) {
    $content . = fread($handle, 10000);
}

fclose($handle);

$content_array = json_decode($content); #JSON content converted to PHP object

WordPress HTTP API method

WordPress gives us a set of very convenient HTTP API (detailed use of reference [WordPress HTTP API](http://codex.wordpress.org/HTTP_API)), we can use the HTTP API is very convenient to realize the above functions.

$content = wp_remote_retrieve_body( wp_remote_get('http://yoursite.com/news'));
$content_obj = json_decode($content); #JSON content converted to PHP object

As you can see, the WordPress method is too simple, one line of code to achieve the PHPfopen method of a few lines of functionality, and the function is more semantic, easier to understand.

Display the contents of the acquisition

The content of the JSON has been captured and converted into a PHP object, so when displaying it, you can just loop through the content of the object.

foreach ($content_obj->data as $key)
    echo $key->title; }
}

Properly formatting the text above displays the same effect as calling WordPress content directly.

Related Posts

0 Comments

    1. It's possible that the plugin version was updated and the call method changed, so you can post the code to see.

  1. Hello blogger, I would like to ask you a question, I want to write some web interface for my wordpress website, through the web interface can query the desired data, I searched the internet and found the answer said to use the JSON API plugin, after I installed it I don't know how to query the specific data of a specific blog, in addition, I have some special needs, I need to return the value of the customized field or write the customized value of a custom field. When I saw your blog, I think it should be what I want to find, but I don't know how to use you this method, can you say in a little more detailed, thanks to the blogger!

    1. The official documentation describes it very clearly: http://v2.wp-api.org/reference/posts/. If you just call a small part of the data, you can completely write an interface by yourself.

  2. Hi blogger, I'm just learning wordpress. I've installed the json api, but I don't know how to use it.

Leave a Reply

Your email address will not be published. Required fields are marked *