需求:將第三方api的前3000條數據全部讀取出來,存入對應的數據庫字段
第三方api:http://pub.cloudmob.mobi/publisherapi/offers/?uid=92&key=d4bab08884781dbf2bede528e27d243d&limit=1000&page=1
sql代碼:
/* Navicat MySQL Data Transfer Source Server : test Source Server Version : 50714 Source Host : localhost:3306 Source Database : test Target Server Type : MYSQL Target Server Version : 50714 File Encoding : 65001 Date: 2018-03-04 10:02:51 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for offers -- ---------------------------- DROP TABLE IF EXISTS `offers`; CREATE TABLE `offers` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `description` text NOT NULL, `country` varchar(255) NOT NULL, `allowedtraffic` varchar(255) NOT NULL, `oid` varchar(10) NOT NULL, `avail` varchar(255) NOT NULL, `name` varchar(255) NOT NULL, `link` text NOT NULL, `preview` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=25575 DEFAULT CHARSET=utf8;
php代碼:
<?php //思路: // 1.先通過php的curl將數據取出來,轉換為對象 // 2.連接數據庫,做預處理 // 3.將取出來的值轉換為數組,並綁定數據庫參數 // 4.執行sql操作,數據抓取成功 //ps:數據的初始化及url會話的關閉只能執行一次,所以放在for循環的后面 $curl = curl_init(); $page=1; for($j=0;$j<3;$j++){ $url="http://pub.cloudmob.mobi/publisherapi/offers/?uid=92&key=d4bab08884781dbf2bede528e27d243d&limit=1&page=$page"; // echo $url; curl_setopt($curl, CURLOPT_URL,$url ); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($curl); // 將json字符串轉換為對象 $data=json_decode($data); $con=mysqli_connect("localhost","root","","test"); if (!$con->connect_error) { echo $con->connect_error; } mysqli_set_charset($con,"gb2312"); $sql="INSERT INTO offers (description,country,allowedtraffic,oid,avail,name,link,preview)VALUES ( ?,?,?,?,?,?,?,?);"; $sql_stmt=$con->prepare($sql) or die($con->error); for ($i=0; $i <1; $i++) { // 將對象的值轉換為數組 $oid=json_encode($data->data[$i]->oid); $avail=json_encode($data->data[$i]->avail); $name=json_encode($data->data[$i]->name); $link=json_encode($data->data[$i]->link); $preview=json_encode($data->data[$i]->preview); $allowedtraffic=json_encode($data->data[$i]->allowedtraffic); $description=json_encode($data->data[$i]->description); $country=json_encode($data->data[$i]->country); $sql_stmt->bind_param('ssssssss',$description,$country,$allowedtraffic,$oid,$avail,$name,$link,$preview); $b=$sql_stmt->execute(); } if (!$b) { echo "操作失敗".$sql_stmt->error; }else{ echo "操作成功"; } //釋放 $page=$page+1; $con->close(); } curl_close($curl); ?>
