Turn string to variables?
I'm trying to make a facebook app around the game Miscrits: World Adventure The idea is to make a PVP ladder.
In order for this to work I want the app to get the player information automatically. The info is stored here: http://miscrits.brokenbulbstudios.com/player/info (unique to each player) The result that it returns looks like this > http://pennygasm.com/info.htm
there is a bold area and I have separated the info to make it easier to read. I need each of the bold values to be stored in a variable. so that I can do some calculations and create a player rank etc.
The player would visit my app and click "Join the Ladder" then it would get the info from the miscrits url. I'm guessing the player would need to return periodically to update their information? it could auto update when the user vis开发者_Python百科its the page...
Anyway... how do I turn that information into some variables?
Those strings look like valid JSON. In PHP 5.2+ you can use json_decode() to convert a json string into objects/arrays chock full of variables :)
see this:
http://php.net/manual/en/function.json-decode.php
and try this:
// grab the JSON data and stuff it in a variable
$json = file_get_contents("http://miscrits.brokenbulbstudios.com/player/info", true);
// decode to an associative array using json_decode()
$decoded = json_decode($json, true);
//check out what's in there
print_r($decoded);
The data looks to be JSON, so you should just be able to use a JSON parser to read that data. PHP has one in the form of json_decode
, which returns an associative array with the data.
First of all, however, you should familiarize yourself with JSON and its syntax before working with the data contained in it. If you already know JavaScript or Python, you should recognize this as object/array notation and dictionaries/lists, respectively.
An example:
$myvar = json_decode('{
"hello" : 1
"there" : [ "a", "b", "c" ]
}');
... would become, in PHP:
$myvar = array(
"hello" => 1,
"there" => array("a", "b", "c")
);
... after a json_decode
.
The result that is returned is called JSON (http://www.json.org/ or http://en.wikipedia.org/wiki/JSON). Javascript has a function called eval that can be used to evaluate the string into a JSON object. In fact you can use eval to evaluate any string into code. This would require code like the following:
eval('var YourVariableName ='+ReturnedJSONData);
You could then acces the with code like s:
YourVariableName.JSONPropertyName;
I wouldn't be supprised though if the API your using couldn't return JSONP (http://en.wikipedia.org/wiki/JSON) that could be evaluated automatically into JSON.
精彩评论