在一个目录中,我有很多包含一些常见数据的.txt文件,例如:
name: XXX
surname: YYY
age: ZZZ
我的问题是为每个txt文件读取这些信息并为每个通信字段填充mysql数据库:name,surname,age。 由于txt文件非常庞大,我只需要处理每个文件的标题(前15行),其中存储了我需要的信息。但是在标题中我需要的信息没有以相同的方式格式化,所以我认为使用正则表达式可能是最好的选择。 有人能帮助我吗?
以下几行是我现在正在使用的代码。如何以及在哪里修改代码以达到我的目标?
<?php
$content = file_get_contents("myfile.txt");
$lines = explode("\n", $content);
foreach ($lines as $line) {
$row = explode(":", $line);
$query = "INSERT INTO tablename SET val1 = '" . trim($row[0]) . "', val2 = '" . trim($row[1]) . "'";
mysql_query($query);
}
?>
答案 0 :(得分:2)
这就是您所需要的:
<?php
//create a mysqli connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Get all the files inside a directory
$dir_iterator = new RecursiveDirectoryIterator("/path/to/txt/folder");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
$content = file_get_contents($file);
for ($x=0; $x<15; $x++)
{
preg_match_all('/name:(.*?)\s+surname:(.*?)\s+age:([0-9]+)/sim', $content, $results, PREG_PATTERN_ORDER);
$name = $results[1][$x];
$surname = $results[2][$x];
$age = $results[3][$x];
mysqli_query($con,"INSERT INTO Persons (name, surname, age)
VALUES ('$name', '$surname', '$age')");
}
}
mysqli_close($con);
?>
备注:强>
上面的代码适用于PHP 5
正则表达式不是防弹,你可能需要稍微调整一下以满足你的需求
确保使用与INSERT查询匹配的字段创建数据库...
答案 1 :(得分:2)
根据我的经验,在PHP中编写批处理作业是不切实际的。但是,在你的帖子中你提到你想使用crontab,所以我认为你使用的是Linux,在这种情况下你可以使用Bash。
创建一个脚本:/home/yourid/bin/processdata.sh
#!/bin/bash
# set-up some variables
outstanding="/some/dir/outstanding"
processed="/some/dir/processed"
tempfile="/tmp/$$.sql"
# set a trap to delete our ${tempfile} on exit or ctrl+c
trap "rm -f ${tempfile}" EXIT INT
# list each .txt file in the outstanding directory
ls -1 ${outstanding}/*.txt | while read filename
do
# stash the data after the ":" into a bash variable
name=$(awk -F":" '/^name/ { print $2 }' ${outstanding}/${filename})
surname=$(awk -F":" '/^surname/ { print $2 }' ${outstanding}/${filename})
age=$(awk -F":" '/^age/ { print $2 }' ${outstanding}/${filename})
# echo a mysql command into our ${tempfile}
echo "INSERT INTO some_table (name,surname,age) VALUES(\"${name}\",\"${surname}\",\"${age}\")" > ${tempfile}
# run a mysql command using these variables
mysql --user=username --password=password db_name < ${tempfile} || {
# if there is a problem, shout about it
echo "Error while processing file: ${outstanding}/${filename}"
# break the loop (to leave the file in ${outstanding}
break
}
# move the file out of the way
mv ${outstanding}/${filename} ${processed}/
done
然后添加一个crontab条目,每5分钟运行一次:
*/5 * * * * /home/yourid/bin/processdata.sh >> /home/yourid/logs/processdata.log 2>&1
有些注意事项:
希望有所帮助。
答案 2 :(得分:1)
我认为可以用这样的东西来完成。
<?php
$INPUT_DIR="inputdir";
$OUTPUT_DIR="processed";
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
function process_file($fileIn) {
// Read the content
$content=file($fileIn); // If they are small
$data=array();
foreach($content as $line) {
$explosion = explode(":", $line); // Use this to parse the file. Doesn't work with : inside the value
$key=strtolower($explosion[0]); // before :
$value=ltrim($explosion[1]); // after :, remove initial space
$data[$key]=$value;
}
// Write the content
if (empty($data["name"] || empty($data["surname"] || empty($data["age"]) {
error_log("Incomplete fields file found at ". $fileIn);
return false;
}
$myquery = "INSERT into ages (name,surname,age) values (:name, :surname, :age)";
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
return $sth->execute(array(':name' => $data["name"], ':surname' => $data["surname"], ':age' => $data["age"]));
}
// Create output dir if not exists
if(!is_dir($OUTPUT_DIR)) {
mkdir($OUTPUT_DIR)
}
// Get list of files in INPUT_DIR
$files_to_process = glob($INPUT_DIR."/*");
foreach($files_to_process as $fileIn) {
echo basename($fileIn). "\n";
if(process_file($fileIn)) {
rename($fileIn, $OUTPUT_DIR."/".basename($fileIn));
}
}
?>
事实上,我认为您可以使用Mirth Connect之类的集成引擎来获取文件输入和SQL输出。它可能更强大。
答案 3 :(得分:0)
以下是一个简单的示例:
$text = <<<TXT
name: XXX
surname: YYY
age: ZZZ
TXT;
$final = array();
foreach(explode("\n", $text) as $line) {
list($key, $data) = explode(': ', $line);
$final[$key] = $data;
}
print_r($final);
// Array ( [name] => XXX [surname] => YYY [age] => ZZZ )