0

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"></script>
</head>

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

2 Answers 2

3

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

?>
Sign up to request clarification or add additional context in comments.

2 Comments

I thought I might have to do this, seems a shame to parse data which is already in a data structure.
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.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.