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?
LVL 7
Robert SaylorSenior DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
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.
Ray PaseurCommented:
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

hieloCommented:
>> 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

C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Robert SaylorSenior DeveloperAuthor Commented:
This was not what I was after. I ended up contracting this work out so will close the request now.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
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?
Robert SaylorSenior DeveloperAuthor Commented:
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.
Ray PaseurCommented:
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)!
Robert SaylorSenior DeveloperAuthor Commented:
I contracted the solution out to a freelancer.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JSON

From novice to tech pro — start learning today.