远程站点正在提供js文件中的数据结构。从PHP访问JS数据
我可以将此文件包含在我的页面中以访问数据并将其显示在我的页面中。
<head>
<script type="text/javascript" src="http://www.example.co.uk/includes/js/data.js"></script>
</head>
有谁知道我如何使用PHP来获取这些数据并将其存储在数据库中?
远程站点正在提供js文件中的数据结构。从PHP访问JS数据
我可以将此文件包含在我的页面中以访问数据并将其显示在我的页面中。
<head>
<script type="text/javascript" src="http://www.example.co.uk/includes/js/data.js"></script>
</head>
有谁知道我如何使用PHP来获取这些数据并将其存储在数据库中?
您应该直接通过例如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
?>
你可以抓住通过卷曲或其他一些HTTP下载库/函数的文件。然后,解析数据。如果幸运的话,数据是JSON格式,您可以使用PHP函数将其转换为PHP数组。然后,遍历数组中的项目,将每个项目插入到数据库中。
我想我可能不得不这样做,似乎是一个耻辱,以解析已经在数据结构中的数据。 – 2008-11-28 19:19:04