...

View Full Version : API (Grab data and place into database)



Blockis
04-19-2012, 07:58 PM
If I want to grab data from an API, how can I do this?

I'm given a URL with parameters like a secret key, and the page renders this:
http://i.imgur.com/ma86X.png

What would I do to import this data to a MySQL database? I understand the querying to place the info in, I'm confused as to how I can grab the information off of this page. (Again, it's just a URL, and it's not on my server)

I can change the format that it outputs, but I felt like PHP may be the easier one?

angst
04-19-2012, 08:02 PM
this is just a multi-dimensional array..

read this: http://php.net/manual/en/language.types.array.php
and this: http://php.net/manual/en/control-structures.foreach.php

pretty straight forward.

Blockis
04-19-2012, 08:13 PM
I know what it is, but how do I grab it off of an external server? How do I physically bring it over to my code?

angst
04-19-2012, 08:16 PM
ah ok, well you could use CURL, something like this:



$ch = curl_init("http://www.SomeUrl.com/Server.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // forces response into return string, not echo
curl_setopt($ch, CURLOPT_HEADER, 0);
$Response = curl_exec($ch);
curl_close($ch);

echo $Response;

Blockis
04-19-2012, 08:29 PM
You are THE MAN :D

So how would I start the importing to my database? Is it weird that the array isn't associated as a variable? (Just looking at examples from the PHP.net link, most of the examples are with $var = array where what I'm given just starts off with array(...))

It makes more sense to connect to the database before doing the foreach's right?

angst
04-19-2012, 08:35 PM
yes, connect to the database before you start the loops. you'll need to use a few loops to make this happen.

once you get to the array with the data you want, insert the values. this looks like a transaction response. normally I would make a table in the database for it, then make each field with the same names as those return. this way you would have a dynamic insert, something like this;



$Insert = "";
foreach ($arr as $key => $value) {
$Insert .= trim($key) . " = '" . mysql_real_escape_string(trim($value)) . "'";
}
mysql_query("INSERT INTO YourTable SET " . rtrim($Insert, ",") );

Blockis
04-19-2012, 09:42 PM
But how do I get through the first array, and extract the
'data' => array array?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum