<?php
header("Content-type: text/html; charset=utf-8");
//连接数据库
try{
$pdo = new PDO("mysql:host=localhost;dbname=xxxxxx","root","xxxxxx");
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo"数据库连接失败".$e->getMessage();
}
//设置时区
date_default_timezone_set("PRC");
//采集地址
$url = 'xxxxxx';
$str = file_get_contents($url);
$arr = json_decode($str,true);
foreach($arr as $val){
//组装数据入库,例如:
$title = $val['title'];
$content= $val['content'];
$addtime = $val['addtime'];
//ignore 忽略主键与唯一ID重复的元素,不出错
$sql1 = "INSERT ignore INTO `gao`( `id`, `title`, `content`, `addtime`) VALUES (null,'".$title."','".$content."','".$addtime."')";
$stmt1 = $pdo->prepare($sql1);
$res = $stmt1->execute();
}
if($res){
die('success');
}else{
exit('fail');
}
PHP数据采集写入数据库
最新推荐文章于 2024-09-08 23:00:10 发布