tags:

views:

145

answers:

2

A remote site is supplying a data structure in a js file.

I can include this file in my page to access the data and display it in my page.

<head>
    <script type="text/javascript" src="http://www.example.co.uk/includes/js/data.js"&gt;&lt;/script&gt;
</head>

Does anyone know how I use PHP to take this data and store in it a database?

+3  A: 

You should GET that file directly, via, for example, CURL. Then parse it, if it comes in JSON, you can use json-decode.

Simple example (slightly modified version of code found here):

<?php
$url = "http://www.example.co.uk/includes/js/data.js";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
...

$output = curl_exec($ch);
$info = curl_getinfo($ch);

if ($output === false || $info['http_code'] != 200) {
  $error = "No cURL data returned for $url [". $info['http_code']. "]";
  if (curl_error($ch))
    $error .= "\n". curl_error($ch);
  }
else {
  $js_data = json_decode($output);
  // 'OK' status; save $class members in the database, or the $output directly, 
  // depending on what you want to actually do.
  ...
}

//Display $error or do something about it

?>
Vinko Vrsalovic
I thought I might have to do this, seems a shame to parse data which is already in a data structure.
Mark Sailes
You would have to parse the data regardless of how it was stored in the Javascript. Unless, of course, it's binary data you can insert directly into your database file. But that's unlikely, unsafe, and unsane.
strager
A: 

You can grab the file via CURL or some other HTTP downloading library/function. Then, parse the data. If you're lucky, the data is in a JSON format and you can use a PHP function to convert it into a PHP array. Then, iterate through the items in the array, inserting each into your database.

strager