遠程站點正在提供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