Accessing JS data from PHP

The remote site provides a data structure in a js file.

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

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

      

Does anyone know how I am using PHP to store this data and store the database in it?

0


source to share


2 answers


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

Simple example (slightly modified version of found code 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

?>

      

+3


source


You can grab the file via CURL or other HTTP download library / function. Then analyze the data. If you're in luck, the data is in JSON format and you can use a PHP function to convert it to a PHP array. Then iterate over the elements in the array, inserting them into your database.



0


source







All Articles