从PHP访问JS数据

时间:2008-11-28 19:07:54

标签: php javascript

远程站点在js文件中提供数据结构。

我可以在我的页面中包含此文件以访问数据并将其显示在我的页面中。

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

有谁知道我如何使用PHP来获取这些数据并将其存储在数据库中?

2 个答案:

答案 0 :(得分:3)

您应该直接获取该文件,例如CURL。然后解析它,如果它是JSON,你可以使用json-decode

简单示例(找到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

?>

答案 1 :(得分:0)

您可以通过CURL或其他一些HTTP下载库/功能获取文件。然后,解析数据。如果幸运的话,数据采用JSON格式,您可以使用PHP函数将其转换为PHP数组。然后,遍历数组中的项目,将每个项目插入到数据库中。