Make an iPhone App Using the Envato API

Apr 14th in PHP by Hayden Gascoigne

With the release of the new Envato Marketplace API, third-party developers now have access to a wealth of information to create all kinds of useful applications. This tutorial will teach you how to make your very own iPhone app using data from the new API. Even if you don't have an iPhone, you can still learn the basics about using PHP and JSON.

PG

Author: Hayden Gascoigne

I'm a freelance web developer from the United States. I also run my own web server and plan to major in computer science. Follow me on Twitter @haydengascoigne92.

Before We Begin

The app we will be creating is based off of my iPhone app, Envato Marketplace Mobile. While we won't be recreating the entire app, this tutorial will give you a general idea on how it was created. This tutorial is aimed at PHP and JSON beginners and serves as a basis for creating more advanced PHP applications.

Using the API

Before we can start retrieving data using the API, we must learn how to go about accessing it. The API is split up into 5 parts:

  1. Version : determines what version of the API to use.
  2. Username : the user whose data you wish to access.
  3. API-key : similar to a password and is unique to each user and grants access to their data.
  4. set and format : determine what data to access and what format to provide it in.

For more information on the API, click here.

Step 1 - Accessing Our Data

Now that we know what is required to access the API, we are ready to put it into practice. Since we want others to use our awesome app, we need to get a username and API key on the fly; so we are going to retrieve some PHP variables from the browser.

if(isset($_GET['user']) && $_GET['user'] != "")
{
	$userName = $_GET['user'];
	if(isset($_GET['key']) && $_GET['key'] != "")
	{
		$apiKey = $_GET['key'];
	}
	else
	{
		echo 'Api key not set!';
		exit;
	}
}
else
{
	echo 'Username not set!';
	exit;
}

The above code checks to see if the variables user and key have been set - and exits if they haven't. It also checks to make sure that the global variable isn't empty.

Retrieving Our Data

Now that we have our required information, we can go ahead and use it to retrieve our data. To do this we will simply create a url using the format outlined in the introduction.

// Creates a string that will be used to access the API
$json_url = "http://marketplace.envato.com/api/edge/".$userName."/".$apiKey."/vitals+recent-sales.json";

Notice that we are using the "edge" version and are using our previous variables for the username and api-key. Finally, we are going to retrieve the vitals and recent sales data sets in the JSON format.

Now that we have created our url to access the API, we must read its contents so that they may be passed to the json_decode function - which requires an actual json data set, not just a url. So, let's go ahead and use the file_get_contents() function to read the contents of the url.

// Get the contents of the $json_url string
$json_contents = file_get_contents($json_url);

// A little error checking
if(!$json_contents)
{
	echo "Error: The JSON file could not be read. Please check your username and api key.";
	exit;
}

We are finally ready to convert the JSON data to an array so that we can use it in our application. To accomplish this task we will use the json_decode() function which will take the data from our $json_contents variable and output it to an array.

// Output our data to an array
$json_data = json_decode($json_contents, true);

We are using two parameters in this function, the first is the string we wish to decode, and the second tells the function to output the data as an array. That's it! We are now ready to show our data to the user.

Step 2 - Displaying Our Results

We've retrieved our data and now it's time to show it to the user. For the sake of simplicity we will be adding our frontend HTML code into the same file as our PHP code. So go ahead and add the standard HTML document code below your PHP code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Nettuts iPhone App - <?php echo $userName; ?></title>

<link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>
<div id="header">My Nettuts iPhone App</div>
</body>
</html>

Notice that in the <title> tag, I added a simple PHP "echo" statement that will display the user's name in the browser's title bar.

Getting the Username and Balance

Let's go ahead and add a simple div that displays the username retrieved from the API. We could do this using the $userName variable like we used in the page title, however, using JSON is more exciting.

<div id="username"><?php echo $json_data['vitals']['username']; ?></div>

What the above code does is retrieve the username from the vitals array, which is an array within our $json_data array that was created earlier. Makes sense?

Here is the structure of the array used in the API example: Array ( [vitals] => Array ( [username] => ryan [balance] => 32.75 ) )

Next, we want to show the user his balance. This is done the same way as we displayed the username. This time, however, we will simply change from "username" to "balance". The rest is simply for layout and styling.

<div id="content">
<div class="line"><img src="bank_plus.png" alt="Balance" class="icon" />Balance: $<?php echo $json_data['vitals']['balance']; ?></div>
<h3>Recent Sales:</h3>

Listing Recent Sales

The last thing on our agenda is to display the most recent sales for a user. This is a little more complicated than the previous examples, however, if you've ever worked with arrays you should be able to handle it.

<?php
// List Recent Sales
$count = 1;
$salesArray = $json_data['recent-sales'];
foreach($salesArray as $value)
{
	if($count <= 10)
	{
		echo "<div class='line'><img src='plus.png' alt='Sale' class='icon' />Sold ".$value['item']." for <strong>$".$value['amount']."</strong></div>";
		$count = $count + 1;
	}
	else
	{
		break;
	}
}
?>
</div><!--End Content-->

There's a lot to digest here so lets start with the foreach statement. First we create a $salesArray from the recent-sales array within $json_data. This isn't necessary, but I think it looks cleaner. The foreach statement creates a $value for each row in the $salesArray array and allows us to pull information from each row. So, basically you use $value to get data from the row as the foreach statement loops through it.

Next up is the code which is executed each time the foreach statement goes through a row. Instead of showing all of the recent sales I only want to list ten, which is why, if the number of rows checked exceeds ten, it will break the loop. To change the number of rows the statement loops through, just change ten to the number you want. Actually displaying the rows is quite simple, as it requires just echoing out each row inside a div with a small icon. We use the $value to access the sale information from the array. We pull "item", which is the item title and "amount" which is the amount the author made on the sale. Finally "$count + 1" just increases the count of rows the statement has looped through. You should now be all set! Try loading the file on a testing server and see if it works!

If you don't have a Envato Marketplace account, you can use the example login:

  • user: ryan
  • key: 26k6otse2s586e4hcbzjy3quq830t3o4

Step 3 - Designing the Frontend

Adding CSS

Well, our new app works great, but it looks bad - which means it's time to break out some CSS. I assume you know enough to understand the following code as I won't be going into it except for a few things. #browser is used by the iPhone/Touch to make sure that if the page it is too small that it will fill the screen. body.lanscape #browser does the same, however, is for when the browser is in landscape mode.

body {
	background: #efefef;
	margin: 0px;
	padding: 0px;
	font-family: Helvetica;
	-webkit-touch-callout: none;
	-webkit-text-size-adjust: none;
	width: 100%;
	color: #2a2a2a;
}

#browser {
 	/* ensure we always fill the whole screen */
  	min-height: 416px;
}

body.landscape #browser {
  	min-height: 268px;
}

h3 {
	margin-bottom: 5px;
}

p {
	margin: 0 0 5px 0;
}

/*
	Layout
*/

#header {
	padding: 10px 5px 5px;
	height: 30px;
	color: #fff;
	font-size: 22px;
	background: url(header_bg.jpg) repeat-x;
}

#username {
	font-size: 18px;
	font-weight: bold;
	text-transform: uppercase;
	padding: 5px;
	/* WebKit supports text-shadow... so why not make it look pretty */
	text-shadow: 0 1px 0 rgba(0, 0, 0, 0.5);
	color: #fff;
	background: #498929;
	border-top: 1px solid #85c952;
	border-bottom: 1px solid #34661c;
}

#content {
	padding: 5px;
	padding-top: 10px;
}

.icon { vertical-align: text-top; margin-right: 5px; }
.line { padding-bottom: 5px; border-bottom: 1px solid #cccccc; margin-bottom: 5px;}

iPhone Time

It's time to make your great app finally iPhone compatible. This is actually really easy and involves only one line of code.

<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">

Just add the above code right below the <title> tag and it should be the right size for your iPhone or iPod Touch. That code scales the page to the correct size for viewing on the iPhone. The last thing you may need to do is add a homepage icon so your app looks cool when someone adds your iPhone application as a webclip. To do this we add another small line of code that is similar to a favicon.

<link rel="apple-touch-icon" href="apple-touch-icon.png"/>

Well... we're all done! You can see the finished product below.

Conclusion

You've made it to the end. I hope this was a good introduction for those who are still in the beginning stages of using PHP and JSON. You're now ready to make your own killer app using the API and JSON in general.

Now remember, this tutorial is for beginners and those who need a jump-start for using the API.

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Devin Rajaram April 14th

    This is really cool. I bought a dev account on apple but I left my friend to use it since I don’t have a mac yet. I have also got the SDK so when I do get my mac I can develop there.

    ( Reply )
    1. PG

      Taylor Satula April 14th

      Youngave a Dev account could.you add my iPod for the 3.0 software update
      Talkingtofu2@gmail.com

      ( Reply )
  2. PG

    cudazi April 14th

    Thanks Hayden, that’s a great app – useful and a great simple design!

    ( Reply )
  3. PG

    Herb April 14th

    Im guessing you’re actually creating a web-app for the iphone? and not an actual native application. this was not clear i believe…

    ( Reply )
  4. PG

    Steve Jabs April 14th

    You should probably mention that this is a iPhone web application. Not something made with the SDK.

    ( Reply )
  5. PG

    Ryan Hickman April 14th

    I’ve used development kits for iphone before, and I didnt get approved in the store because of that. When using the IUI lib, I was denied. When I used the Mag I was denied. I did get in with phone gap which to me, is one of the best it lets you use the devices internal functionality (accelerometer, gps, etc…)

    Don’t know if Im a fan. I will be a fan if they get an application published using this.

    ( Reply )
  6. PG

    myDevWares April 14th

    Is anyone in such a frenzy about their files that they need to check their sales while on the go? Interesting API…I hope I can find a practical use.

    ( Reply )
    1. PG

      Hayden Gascoigne April 14th

      The main goal of the article is working with JSON and I used the API as my example.

      ( Reply )
  7. PG

    Kevin Quillen April 14th

    Damn, for a second I thought we’d be getting into Obj C and the SDK. Cool nonetheless… Currently working on learning the SDK myself and would be cool to collaborate on some real world scenario apps.

    ( Reply )
  8. PG

    crysfel April 14th

    Thanks for this one!!

    ( Reply )
  9. PG

    lawrence77 April 14th

    cool one thanks! ;)

    ( Reply )
  10. PG

    Shane April 14th

    It’s a nice tutorial, but the iPhone part is the last, small bit. Could that not be applied to quite a few of the tutorials on nettuts? :)

    ( Reply )
  11. PG

    John Wang April 14th

    I think the article title is quite misleading. There’s a difference between iPhone App and iPhone Web App. This tutorial is for the iPhone Web App. Which is a Web App running in the Mobile Safari browser on the iPhone. Not a native application running and using the SDK. Also, there is no cost for making Web Apps for the iPhone, there is a Developer Program cost for developing native Apps.

    For iPhone Web App – http://developer.apple.com/safari/mobile.php
    For iPhone App – http://developer.apple.com/iphone/

    I think the title of the tutorial should be changed to: “Make an iPhone Web App Using the Envato API”

    ( Reply )
    1. PG

      Hayden Gascoigne April 14th

      You’re right. I’ll talk to Jeffrey about getting that changed.

      ( Reply )
  12. PG

    Kai April 14th

    It might be more appropriate to call this an iPhone *web* app, but a good tutorial none the less.

    ( Reply )
  13. PG

    abenson April 14th

    Get an error on my server: URL file-access is disabled in the server configuration

    I’m on shared hosting so I guess no luck for me in changing the php.ini.

    ( Reply )
  14. PG

    Yoosuf April 14th

    b4 3 weeks i was wondering what is API key for Envato and now i realized why its needed!

    ( Reply )
  15. PG

    Taylor Satula April 14th

    I for 5 seconds I went “yay Obj C I get I Lear to make a iPhone app” misleading but good nonetheless.

    ( Reply )
  16. PG

    Chris April 15th

    nice tut. More iPhone Web Apps would be awsome :) I think thats would be a good set of tuts to create.

    ( Reply )
  17. PG

    Chris April 15th

    I didnt realise an iPhone web app was a case of adding a couple of lines in the head so the window is the right size. Will probably never use this, but its good knowledge to have, and I’m sure it could add a few £££ to a quote on doing a web site ;) . Thanks for sharing!

    ( Reply )
    1. PG

      Ethan April 15th

      That was my question too. That is really neat that you can create a iPhone app from virtually any web page :)

      ( Reply )
  18. PG

    Daan April 16th

    That was a great tutorial, and I bookmarked your app on my iPod Touch :D
    I hope this tutorial doesn’t cover too much of my upcoming iPhone webpage development tutorial thingy that I’m currently writing for Nettuts though

    ( Reply )
  19. PG

    TJ April 20th

    Ew PHP thats really lame

    ( Reply )
  20. PG

    jernigani April 21st

    Please don’t include in your tutorial files the words “iPhone app”, if what it really means is “iPhone web app”.

    I kind of got mad at you for confusing your readers.

    ( Reply )
    1. PG

      Hayden Gascoigne April 22nd

      I’ve already sent an email to Jeffrey about it. Also, many other people have already mentioned this.

      ( Reply )
  21. PG

    jernigani April 22nd

    Hey! I’ve taken this tutorial to another level. Check out this link on your iPhone or browser. I’ve taken what the api gives, and expanded it a little more.

    And just used the basic iPhone styling, but it’s really handy on my iPhone.

    http://israeljernigan.com/flashden/iphone2/

    If you’d like the code, I can totally get it to you. The content is my humble information, but I thought it would be better to show real stuff instead of fake results.

    {note to envato} since you’re api is still a bit lacking, I’m using some curl to parse search results from your search page. You can stop me if you don’t like it. My bot’s name is simple “jerniganibot/0.1″

    ( Reply )
  22. PG

    Vinay April 30th

    Has anyone checked http://iwebkit.net/ ? I think thats much better way to make iPhone Web App or atleast iPhone Optimized Web Page.

    ( Reply )
  23. PG

    claude May 28th

    hey can anyone give me the whole thing to create a twitter simple program on my iphone???

    thanks

    ( Reply )
    1. PG

      Jash Sayani July 16th

      What do you mean by “give me the whole thing” ??

      Either use an existing app or build your own!! You cannot expect someone to make an app and give it to you.

      And believe me, making an app is very much fun and exciting!!

      BTW, Great JSON Tutorial !!

      ( Reply )
  24. PG

    MexiChriS August 2nd

    Okay, if anyone is wanting to learn to develop apps for the iPhone, please VOTE for them and get TUTs to make it happen!!! Vote for iPhone site/tutorials bellow! ….Maybe repost this somewhere yourself, to make it happen sooner, think about it!!!

    iPhone Tuts Site:
    http://psdtuts.uservoice.com/pages/2999-vectortuts-site-suggestions-and-feedback/suggestions/220438-iphone-tuts-site

    Learn To Code For iPhone:
    http://psdtuts.uservoice.com/pages/2997-nettuts-tutorial-suggestions/suggestions/155081-learn-to-code-for-iphone

    DEVTuts+:
    http://psdtuts.uservoice.com/pages/2997-nettuts-tutorial-suggestions/suggestions/245744-devtuts-

    ( Reply )
  25. PG

    raj November 20th

    This is a great tutorial but it’s poorly described. This is NOT an iPhone app. It’s a web app that’s iPhone-compatible.

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    November 20th