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

04-19-2012, 08: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:

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?

04-19-2012, 09: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.

04-19-2012, 09: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?

04-19-2012, 09: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);

echo $Response;

04-19-2012, 09: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?

04-19-2012, 09: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, ",") );

04-19-2012, 10: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