我需要在数据库中上传.txt文件。 我的.txt文件看起来很像
Name|Code|Email|Designation|Number|Salary|Age\t
syed|101|syed@gmail.com|trainee|7222877798|6000|21\t
hari|102|hari@gmail.com|trainee|9554512582|6000|23\t
我需要将其与|
然后\t
分开。
获得数组时,第一个实现了我所期望的。但我无法让\t
爆炸..任何人都可以帮助我在这个论坛上?
我的例行程序如下所述
if ($_POST['frmSubmit']) {
$file = $_FILES['frmUpload']['tmp_name']; // Get Temporary filename
$handle = fopen($file,"r"); // Open the file and read
while($strBookData = fgets($handle, 4096)) { // To get Array from .txt
$strDatas[] = $strBookData;
$strTableColumn = count($strBookData);
}
$strDatas = explode("|",implode($strDatas));
printArray($strDatas); exit;
if ($strDatas) {
$strInsertRecords = 0;
$strDuplicationRecords = 0;
if ($strTableColumn == 7) {
for($k=1; $k<count($strDatas); $k++) { //$k=1 is initialized because $k[0] is a header field array.
$strStatus = doCheckDuplication($strDatas[$k]['2']);
if ($strStatus == 0) {
// Insert Code
$strData = $strDatas[$k];
doInsertEmployeeDetails($strData['0'], $strData['1'], $strDatas[$k]['2'], $strData['3'], $strData['4'], $strData['5'], $strData['6']);
$strInsertRecords++; // To Get Inserted Records Count.
} else {
$strDuplicationRecords++; // To Get Duplication Records Count.
}
}
}
}
答案 0 :(得分:1)
您好,这将拆分您提供的文字。
$text = 'Name|Code|Email|Designation|Number|Salary|Age\t
syed|101|syed@gmail.com|trainee|7222877798|6000|21\t
hari|102|hari@gmail.com|trainee|9554512582|6000|23\t';
//remove line endings
$text = str_replace(array("\r\n", "\r", "\n"), "", $text);
$rows = explode('\t', $text);
$data = array();
foreach ($rows as $row){
//don't include empty lines
if(!empty( $row )){
$data[] = explode('|', $row);
}
}
echo '<pre>';
var_export( $data );
输出:
array (
0 =>
array (
0 => 'Name',
1 => 'Code',
2 => 'Email',
3 => 'Designation',
4 => 'Number',
5 => 'Salary',
6 => 'Age',
),
1 =>
array (
0 => 'syed',
1 => '101',
2 => 'syed@gmail.com',
3 => 'trainee',
4 => '7222877798',
5 => '6000',
6 => '21',
),
2 =>
array (
0 => 'hari',
1 => '102',
2 => 'hari@gmail.com',
3 => 'trainee',
4 => '9554512582',
5 => '6000',
6 => '23',
),
);
然而就是说,你的例子中有很多内容正在阅读文件中。如果它不是很大,最好的选择是使用file_get_contents()
来读取整个文件文件一气呵成。否则在本部分
$handle = fopen($file,"r"); // Open the file and read
while($strBookData = fgets($handle, 4096)) { // To get Array from
$strDatas[] = $strBookData;
$strTableColumn = count($strBookData);
}
你最好只是连接文本。
$strDatas = '';
$handle = fopen($file,"r"); // Open the file and read
while($strBookData = fgets($handle, 4096)) { // To get Array from
$strDatas .= $strBookData;
}
然后像我上面那样分裂。
答案 1 :(得分:0)
我认为您应首先使用'\ t'作为分隔符来爆炸,以便将子字符串分隔为\ t(名称|代码|电子邮件|名称|编号|薪资|年龄) 然后使用'|'爆炸每个子字符串作为分隔符。 我希望这可以帮到你