解析JSON插入数据库

时间:2023-03-09 09:19:11
解析JSON插入数据库
<?php
header("Content-Type:text/html;charset=utf-8");
include_once('./mysql.php');
$filename = "F:/heyu.txt";
$handle = fopen($filename, "r");//读取二进制文件时,需要将第二个参数设置成'rb' //通过filesize获得文件大小,将整个文件一下子读到一个字符串中
$contents = fread($handle, filesize ($filename));
$arr = json_decode($contents,true);
$arr=$arr['weibosearchcontent']; $str_target='';
$str_data=''; $conndb=new ConnDB(); foreach($arr as $i=>$msg){
echo $i.'<br>';
foreach($msg as $key=>$val){
//echo $key.'=>'.$val.'<br>';
$str_target.=$key.',';
if($key=='uid'){
$val=str_replace('1001030103','',$val);
} if($key=='titles'){//遍历moods数组 $tmp='';
foreach($val as $t=>$v){
$tmp.=$v.',';
}
$tmp=rtrim($tmp,","); $str_data.='\''.$tmp.'\',';
}
else if($key=='pics'){//遍历moods数组 $tmp='';
foreach($val as $t=>$v){
$tmp.=$v.',';
}
$tmp=rtrim($tmp,","); $str_data.='\''.$tmp.'\',';
}
else if($key=='moods'){//遍历moods数组 $tmp='';
foreach($val as $t=>$v){
$tmp.=$v.',';
}
$tmp=rtrim($tmp,","); $str_data.='\''.$tmp.'\',';
}
else{
$str_data.='\''.$val.'\',';
}
}
//去掉最后的逗号
$str_target=rtrim($str_target, ",");
$str_data=rtrim($str_data, ","); echo $str_target.'<br>';
echo $str_data.'<br>'; $sql='insert into keyword_weibo('.$str_target.') values('.$str_data.')';
$conndb->query($sql); $str_target='';
$str_data='';
} fclose($handle);
?>