我的服务器上有文件示例25295.txt,24565.txt在我的服务器上,文件名是用户ID,文件内容就像
[{"name":"+91 88264 73159","mobile":"+918826473159"},
{"name":"+91 99971 17220","mobile":"+919997117220"}]
我的表结构是这样的:
我想运行一个cron作业,在多个文件的不同行中插入每个名称和移动设备user_id
(文本文件的名称是用户ID)。每个文件中有大约800条相同的记录,并且还可以通过以下方式修剪手机:
$mobile=str_replace('+','0',$data['mobile']);
$mobile=str_replace(' ','',$mobile);
$mobile=substr($mobile, -10);
如何做同样的事情,上传后我想从服务器上删除文本文件。
答案 0 :(得分:1)
服务器上的文件看起来像JSON。你可以简单地解码它们,然后像往常那样插入它们。
$filePath = '/tmp/somefile.txt';
$contents = file_get_contents($filePath);
$obj = json_decode($contents);
var_dump($cbj);
为了使它更容易,这里是从文件到数据库的整个过程的一个小例子。
// Make your database connection
$link = mysqli_connect('<hostname>', '<username>', '<password>', '<database>');
// Define the file location
$fileLocation = '/tmp/example.txt';
// Retrieve contents
$contents = file_get_contents($fileLocation);
// Convert json to ObjectArray
$persons = json_decode($contents);
// Loop through array and insert
foreach ($persons as $person) {
$number = substr(str_replace(' ', '', str_replace('+', '00', $person->number))), -10);
$stmt = "INSERT INTO persons (id, name, number) VALUES ('".$person->id."', '".$person->name."', '".$number."')";
mysqli_query($link, $stmt);
}
// Remove the file
unlink($fileLocation);
[{"id":14,"name":"John","number":"555-66-77-8"},{"id":24,"name":"Jane","number":"555-77-88-9"},{"id":34,"name":"Santa","number":"555-6-77-77"}]
答案 1 :(得分:0)
我的代码是针对一个文件25295.txt
<?php
$conn = new mysqli('localhost','root','password','dbname');
if($conn){
$filename = '25295.txt';
$filePath = '/path_to_file/'.$filename;// file path
$contents = file_get_contents($filePath);
$userID = rtrim($filename,".txt");// this will give 25295
$data = json_decode($contents,true);// this will give associative array
$stmt = $conn->prepare("INSERT INTO table_name(user_id,name, mobile) VALUES(?,?, ?)") or die($stmt->error);
foreach($data as $insertRow){
foreach($insertRow as $key => $value){
$insertData[$key] = $value;
}
extract($insertData);// this will give variable from array with name same as key of array
$stmt->bind_param('iss',$userID,$name,$mobile);
$stmt->execute();
}
}