Skip to content
TORNLIFE More

PHP/HTML API Tutorial

Started by AAW [1525734] on in API Development.

25 replies · 739 views · thread synced · 7 days ago · View on torn.com
About this thread

Posts archived: 26 / 26 posts (100%) · the total is Torn's reply count + the opening post at the last fetch

Counted by TornLife from the archived posts.

Archived posts
26
Discussion span
→
Authority score
54 / 100
Historical score
23 / 100
Story score
39 / 100
Engagement score
69 / 100

People posting, likes and official posts are not counted for this thread yet: on threads longer than one page they come from a periodic pass over the archive, which has not covered it.

AAW [1525734]

Just a small tutorial on how you could use Torn's new API system.Firstly you need too get a web host or if your just starting out, you can use WAMP, its a localhost php server.

Step 1: Once you have your chosen type of server up and running you want too go ahead and start by creating a file called "index.php"

Step 2: Once this file has been created you want too start by adding a HTML base.
"<html>
<head>
<title>AAW's API Tutorial</title>
</head>
<body>"

This is were the php code will be put!!!

</body></html>"

Step 3: add the following code too your HTML base
"<?php
$json = file_get_contents("API LINK HERE");
$obj = json_decode($json);
?>"

Step 4: Once you've got all that setup it should look a little like this!
"<html>
<head>
<title>Torn Statistics</title>
</head>
<body>
<?php
$json = file_get_contents("API LINK HERE");
$obj = json_decode($json);
?>
</body>
</html>"

Step 5: If you would like too grab a value from the API simply just add below
$obj = json_decode($json);
echo "Example" . $obj->timestamp;
This above will display the current timestamp within Torn.


Heres a photo of what it should look like!
[image: i67.tinypic.com]


Plornt [1799359]

Okay two ways. First up the jQuery way:


var API_KEY = "mykey";$.get("http://api.torn.com/user/?key="+API_KEY, function (data) { alert(data.player_id + " is my ID");});
Second up the non jQuery way:

This way may look way more complicated but realistically this one has a lot more purely because I spent a little time making it more tailored to the torn API.


var API_KEY = "mykey";function getResult (obj) { var selections = (obj.hasOwnProperty("selections") ? obj.selections : null); var route = obj.route; var entity = obj.entity; var success = obj.success; var || function (e) { console.error(e); }; if (typeof(selections) != "array" && selections !== null) { selections = [selections]; } if (typeof(entity) == "array") { entity = entity.join(","); } var req = new XMLHttpRequest(); req.open("GET","http://api.torn.com/"+route+"/"+entity+"?key="+API_KEY+(selections != null ? "&selections="+selections.join(",") : "")) req.send(); console.log("Sending request"); req.onerror = onerror; req.onreadystatechange = function () { if (req.readyState == 4) { if (req.status != 200) { onerror(req.statusText); return; } try { var data = JSON.parse(req.responseText); if (data.hasOwnProperty("error")) { onerror(data.error); return; } success(data); } catch (e) { onerror(e); } } }}getResult({ route: "user", success: function (profileInfo) { var myID = profileInfo.player_id; alert(myID); }});
Meme_Raven [1891116]

I'm no expert in PHP, so don't scold me, but here's my example to get Networth.

<?php
/* Torn API Documentation test - first revision */
$apiKey = "YOUR-API-KEY";
$apibase = "http://api.torn.com/user/?selections=profile,basic,icons,networth,bazaar,display&key=".$apiKey;
$response = file_get_contents($apibase); $outputPublic = json_decode($response, true);

#networth
$networthArray=Array($outputPublic["networth"]);
$networthFromArray=number_format($networthArray[0]["total"]);
print_r($networthFromArray);
?>
Metzen [1965612]

Is there something wrong with my php? I get the following error with aaw and toms example:


Warning: file_get_contents(http://api.torn.com/torn/USERIDHERE.json?selections=stats&key=MYKEYHERE): failed to open stream: Connection refused in /srv/disk6/2003124/www/mydomainhere.org/metzen.php on line 7
Example
Metzen [1965612]

<html>
<head>
<title>Torn Statistics</title>
</head>
<body>
<?php
$json =file_get_contents("http://api.torn.com/torn/MYIDNUMBER.json?selections=stats&key=MYKEY");
$obj = json_decode($json);
echo "Example" . $obj->timestamp;
?>
</body>
</html>
Plornt [1799359]

Your hosting provider might have PHP settings that prevent access via file_get_contents, give cURL a try: http://php.net/manual/en/curl.examples.php
Metzen [1965612]

Thank you aaw and tom. I switched over to one of my other hosts and it's working now.

How would I get energy? I Get the following error when using the following url:
http://api.torn.com/user/?selections=Bars&key=mykey

And changed code to echo "Energy" . $obj->energy;

Catchable fatal error: Object of class stdClass could not be converted to string in /home2/rgg /public_html/metzen.php on line 9
Plornt [1799359]

That error means that you are trying to convert a class into a string (which it cannot do). I'd recommend doing a var_dump($obj) to see what exactly you are receiving.

In this case you are accessing the energy object but you've not gone far enough down to get to something that can be converted into a string.

Eg. Heres the energy object for myself:


energy: { current: 105, maximum: "150", increment: 5, interval: 600, ticktime: 475, fulltime: 5275}
In PHP when using json_decode, it goes through the JSON object and converts into object, array, integer, float or string.. A very quick explanation In JSON {} means "this is an object", [] means this is an array, "anything in quotes" is a string and a number is a number. So for example to get the current energy you have you would use:

$obj->energy->current

cordlesscord1 [1838706]

I made one which shows all the main bars :)

<html>
<head>
<title>Torn Info</title>
</head>
<body bgcolor="DCDCDC">

<?php
$json =file_get_contents("http://api.torn.com/user/?selections=Bars,money&key=J2fIt");
$obj = json_decode($json);
echo "Energy=" . $obj->energy->current;
echo "/" . $obj->energy->maximum;
?>

<p>
<?php
echo "Nerve=" . $obj->nerve->current;
echo "/" .$obj->nerve->maximum;
?>
</p>

<p>
<?php
echo "Happy=" . $obj->happy->current;
echo "/" . $obj->happy->maximum;
?>
</p>

<p>
<?php
echo "Life=" .$obj->life->current;
echo "/" .$obj->life->maximum;
?>
</p>

<p>
<?php
echo "Money=$" . $obj->money_onhand;
?></p>


</body>
</html>
AAW [1525734]
<html>
<head>
<title>Torn Info</title>
</head>
<body bgcolor="DCDCDC">

<?php
$json =file_get_contents("http://api.torn.com/user/?selections=Bars,money&key=J2fIt");
$obj = json_decode($json);
echo "Energy=" . $obj['energy']['current'];
echo "/" . $obj['energy']['maximum'];
?>

<p>
<?php
echo "Nerve=" . $obj['nerve']['current'];
echo "/" .$obj['nerve']['maximum'];
?>
</p>

<p>
<?php
echo "Happy=" . $obj['happy']['current'];
echo "/" . $obj['happy']['maximum'];
?>
</p>

<p>
<?php
echo "Life=" .$obj['life']['current'];
echo "/" .$obj['life']['maximum'];
?>
</p>

<p>
<?php
echo "Money=$" . $obj['money_onhand'];
?></p>


</body>
</html>
Doge-Chan [1962553]

how would i get the $json =file_get_contents("http://api.torn.com/user/?selections=Bars,money&key=J2fIt"); to get the key info from a form?? sorry, i'm a noob when it comes to working with forms and totally new to api usage