使用php从txt文件中提取数据以导入mysql数据库
在一个目录中,我有很多.txt文件,其中包含一些常用数据,例如:使用php从txt文件中提取数据以导入mysql数据库,php,mysql,Php,Mysql,在一个目录中,我有很多.txt文件,其中包含一些常用数据,例如: name: XXX surname: YYY age: ZZZ 我的问题是为每个txt文件读取这些信息,并为每个对应字段(姓名、姓氏、年龄)填充一个mysql数据库。 由于txt文件非常庞大,我只需要处理每个文件的头15行,其中存储了我需要的信息。但是,在标题中,我需要的信息的格式不同,因此我认为使用正则表达式可能是最好的选择。 有人能帮我吗 下面几行是我现在正在使用的代码。如何以及在何处修改代码以达到我的目标 <?php
name: XXX
surname: YYY
age: ZZZ
我的问题是为每个txt文件读取这些信息,并为每个对应字段(姓名、姓氏、年龄)填充一个mysql数据库。
由于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);
}
?>
下面是一个简单的示例,让您开始学习:
$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 )
这就是您需要的:
注:
以上代码适用于PHP5
正则表达式不是防弹的,您可能需要稍微调整它以满足您的需要。
确保创建的数据库中的字段与插入查询匹配…我认为可以使用类似的方法来完成
<?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));
}
}
?>
事实上,我认为您可以使用集成引擎,比如文件输入和SQL输出。它可能更健壮。根据我的经验,用PHP编写批处理作业是不实际的。然而,在你的帖子中,你提到你想使用crontab,所以我假设你使用的是某种风格的Linux,在这种情况下,你可以使用Bash 创建脚本:/home/yourid/bin/processdata.sh 需要注意的一些事项: 该脚本很少进行错误处理。 SQL是从一个存在安全风险的文件执行的,尽管使用$$在某种程度上否定了这一点。 使用的目录必须存在,才能工作。
希望能有所帮助。您已经有了哪些代码?您在哪里需要帮助?你有一份由许多小问题组成的工作:试着把它分解,试着为它们想出一个解决方案,如果一些具体的问题不起作用,回来问一个问题。就目前情况而言,这个问题是一个广泛的回答在这个网站上有用的形式。为什么否定我的问题?因为你应该张贴一些代码。。。我没有投反对票,实际上我正在研究你的答案。哦,对不起,请原谅。我可以编辑我的问题并插入代码。所以我希望我的负利率会被删除。嗨,图加,非常感谢你的代码,我想这会对我很有帮助,特别是preg_match_all part。由于要处理的文件非常大,有没有办法只对每个文件的前15行进行preg匹配检查?提前谢谢!:根据你的评论,我已经更新了答案,只匹配前15条记录。
<?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));
}
}
?>
#!/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
*/5 * * * * /home/yourid/bin/processdata.sh >> /home/yourid/logs/processdata.log 2>&1