首页 > 数据库技术 > 详细

解析JSON插入数据库

时间:2016-04-08 21:23:54      阅读:387      评论:0      收藏:0      [点我收藏+]
<?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);
?>

 

解析JSON插入数据库

原文:http://www.cnblogs.com/zeze/p/5369825.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!