Reading JSON in PHP with only the libraries in WordPress

I want to read JSON data coming in to a server that has just enough PHP installed to run WordPress. I can create new .php files, but I don’t have the admin permissions to add any libraries that aren’t already there.

What’s the easiest way to grab & parse the JSON data out of an http request in this situation?

Related posts

Leave a Reply

4 comments

  1. Thanks for the pointers, all, but the answer I was looking for was a much simpler one. The necessary two lines of code turned out to be:

    $json_data = file_get_contents("php://input");
    $json_data = json_decode($json_data, true);
    

    Line one: Get the json data hitting the page.
    Line two: Parse it into a proper hash.

  2. If you are doing this within the context of WordPress, you should use the built-in HTTP helper functions (http://codex.wordpress.org/HTTP_API). They are simpler than curl. Example:

    $response = wp_remote_get( $url );
    if( is_wp_error( $response ) ) {
       $error_message = $response->get_error_message();
       echo "Something went wrong: $error_message";
    } else {
       echo 'Response:<pre>';
       print_r( $response );
       echo '</pre>';
    }
    

    The above will return something like this:

    Array
    (
        [headers] => Array
            (
                [date] => Thu, 30 Sep 2010 15:16:36 GMT
                [server] => Apache
                [x-powered-by] => PHP/5.3.3
                [x-server] => 10.90.6.243
                [expires] => Thu, 30 Sep 2010 03:16:36 GMT
                [cache-control] => Array
                    (
                        [0] => no-store, no-cache, must-revalidate
                        [1] => post-check=0, pre-check=0
                    )
    
                [vary] => Accept-Encoding
                [content-length] => 1641
                [connection] => close
                [content-type] => application/php
            )
        [body] => {"a":1,"b":2,"c":3,"d":4,"e":5}
        [response] => Array
            (
                [code] => 200
                [message] => OK
            )
    
        [cookies] => Array
            (
            )
    
    )
    

    Then you can use json_decode() to change the json into an array: http://www.php.net/manual/en/function.json-decode.php

  3. With cURL and json_decode, you’d do it like this. If you’re running WordPress, chances are these are available.

    $session = curl_init('http://domain.com/'); // HTTP URL to the json resource you're requesting
    curl_setopt($session, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    $json = json_decode(curl_exec($session));
    curl_close($session);
    echo $json;