Link to home
Start Free TrialLog in
Avatar of Robert Saylor
Robert SaylorFlag for United States of America

asked on

PHP JSON

Hi, I have limited experience with JSON. What I want to do is from a remote location post JSON data to my server then my server would parse the JSON data.

Any tutorials on this?
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Conceptually, JSON is a string of characters used as a data transport wrapper, similar to XML, but more efficient.
http://json.org/

No tutorials, but it's easy to do with PHP.  You can interpret a JSON string into a PHP object with the JSON-related functions (they also go the other way).
http://php.net/manual/en/ref.json.php

Not sure what you mean by "post JSON data to my server..."  Can you tell us a little more about the app requirements?  Maybe we can give you an example.
Here's a code snippet from another E-E question about JSON and PHP.
<?php // demo/json_decode_show_errors.php

/**
 * JSON stands for JavaScript Object Notation
 * http://json.org/
 *
 * JSON support in PHP does not have very good error handling
 *
 * JSON strings are all UTF-8
 * http://www.experts-exchange.com/articles/11880/Unicode-PHP-and-Character-Collisions.html
 *
 * PHP man page references
 * http://php.net/manual/en/json.constants.php
 * http://php.net/manual/en/function.json-decode.php
 * http://php.net/manual/en/function.json-encode.php
 * http://php.net/manual/en/function.json-last-error.php
 * http://php.net/manual/en/function.json-last-error-msg.php
 */
error_reporting(E_ALL);
echo '<pre>';

// SEE TEST DATA AT http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28523915.html#a40339939
$jso = <<<EOD
{"id":"tag:search.twitter.com,2005:389903668427763712","objectType":"activity","actor":{"objectType":"person","id":"id:twitter.com:91239297","link":"http://www.twitter.com/OGkush103","displayName":"WalkingLick74","postedTime":"2009-11-20T01:21:39.000Z","image":"https://si0.twimg.com/profile_images/378800000593715086/755411d8bdc495472c2d7ed50e319582_normal.jpeg","summary":"Self-Made, Self Paid..... I always had the mind to get it like a man, head first bout my younging Ean! #YOLO","links":[{"href":null,"rel":"me"}],"friendsCount":468,"followersCount":677,"listedCount":0,"statusesCount":25504,"twitterTimeZone":"Alaska","verified":false,"utcOffset":"-28800","preferredUsername":"OGkush103","languages":["en"],"location":{"objectType":"place","displayName":"Boston George Crib"},"favoritesCount":26},"verb":"post","postedTime":"2013-10-15T00:00:53.000Z","generator":{"displayName":"Twitter for iPhone","link":"http://twitter.com/download/iphone"},"provider":{"objectType":"service","displayName":"Twitter","link":"http://www.twitter.com"},"link":"http://twitter.com/OGkush103/statuses/389903668427763712","body":"You a killer you on twitter, You'n do NO talking","object":{"objectType":"note","id":"object:search.twitter.com,2005:389903668427763712","summary":"You a killer you on twitter, You'n do NO talking","link":"http://twitter.com/OGkush103/statuses/389903668427763712","postedTime":"2013-10-15T00:00:53.000Z"},"favoritesCount":0,"location":{"objectType":"place","displayName":"Mississippi, US","name":"Mississippi","country_code":"United States","twitter_country_code":"US","link":"https://api.twitter.com/1.1/geo/id/43d2418301bf1a49.json","geo":{"type":"Polygon","coordinates":[[[-91.65500899999999,30.146096],[-91.65500899999999,34.996099],[-88.097888,34.996099],[-88.097888,30.146096]]]}},"geo":{"type":"Point","coordinates":[31.99686058,-88.72688823]},"twitter_entities":{"hashtags":[],"symbols":[],"urls":[],"user_mentions":[]},"twitter_filter_level":"medium","twitter_lang":"en","retweetCount":0,"gnip":{"matching_rules":[{"tag":null}],"language":{"value":"en"}}}
EOD;

// IF DECODING SUCCEEDS
$obj = json_decode($jso);
if ($obj)
{
    // SHOW SOME PARTS OF THE OBJECT
    $x = $obj->objectType;
    $y = $obj->actor->displayName;
    echo PHP_EOL . "$x $y" . PHP_EOL;

    // ACTIVATE THIS TO SHOW THE ENTIRE OBJECT
    // var_dump($obj);
}

// IF DECODING FAILS?
if (!$obj) echo json_last_error_message();

function json_last_error_message()
{
    static $errors = array
    ( JSON_ERROR_NONE           => null
    , JSON_ERROR_DEPTH          => 'Maximum stack depth exceeded'
    , JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch'
    , JSON_ERROR_CTRL_CHAR      => 'Unexpected control character found'
    , JSON_ERROR_SYNTAX         => 'Syntax error, malformed JSON'
    , JSON_ERROR_UTF8           => 'Malformed UTF-8 characters, possibly incorrectly encoded'
    )
    ;
    // ADD THESE AT PHP 5.5+ OR USE json_last_error_msg()
    if (defined('JSON_ERROR_RECURSION'))        $errors[JSON_ERROR_RECURSION]        = 'One or more recursive references in the value to be encoded';
    if (defined('JSON_ERROR_INF_OR_NAN'))       $errors[JSON_ERROR_INF_OR_NAN]       = 'One or more NAN or INF values in the value to be encoded';
    if (defined('JSON_ERROR_UNSUPPORTED_TYPE')) $errors[JSON_ERROR_UNSUPPORTED_TYPE] = 'A value of a type that cannot be encoded was given';

    $error = json_last_error();
    return array_key_exists($error, $errors)
    ? $errors[$error]
    : "Unknown error ({$error})"
    ;
}

Open in new window

Avatar of hielo
>> What I want to do is from a remote location post JSON data to my server
OK, then if you were to send a "raw post" such as:
{"username":"John", "age":33}

to read it, try using:
$data = json_decode(file_get_contents("php://input"));

echo $data->username; //should give you John
echo $data->age;

Open in new window


On the other hand if you are submitting a JSON string via browser using a textarea - ex:
<form method="post" action="yourscript.php">
<textarea name="person_info">{"username":"John", "age":33}</textarea>
...
</form>

Open in new window

Then you can get the JSON string using:
$data = json_decode( $_POST['person_info'] );
echo $data->username; //should give you [b]John[/b]
echo $data->age;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Robert Saylor
Robert Saylor
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What were you after?  
Can you tell us a little more about the app requirements?  Maybe we can give you an example.
It seems like you didn't answer, eh?
Avatar of Robert Saylor

ASKER

Ray,

I have one developer updating our IOS and Android app that will send JSON data to a remote URL. The JSON is going to be sent via POST to the URL. The URL then needs to read the POSTED JSON data then the data is converted to an array and then inserted into my database.

I contracted a freelancer to do this part for me being JSON is an area I don't work in. The database side I am doing.
OK, sorry.  I don't understand.  This is such an obviously simplistic application that it seems like it's almost not a question.  Anyway, good luck with your project (and please don't overpay for a solution)!
I contracted the solution out to a freelancer.