[英]How to get specific rows in a txt file in PHP?
這是我的問題,我正在嘗試制作一個腳本,以便為我得到的每個新txt文件在數據庫中創建一個新表。 這部分還可以,但是我想在txt文件中獲取一些特定的行或單詞以更新表。
這是我的代碼:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "exctraction";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
foreach (glob("*.txt") as $filename)
{
$sql = "CREATE TABLE IF NOT EXISTS `$filename` (
`id` int(100) unsigned NOT NULL AUTO_INCREMENT,
`device` varchar(30) NOT NULL,
`label` varchar(30) NOT NULL,
`configured` varchar(3) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;";
if ($conn->query($sql) === TRUE)
{
echo "<b>La table ".$filename." "." a été créée avec succès.</b> </br>";
}
else
{
echo "<u>Erreur lors de la création de la table :</u> </br>" . $conn->error;
}
$file = fopen( $filename, "r" );
$content = "";
for( $i = 0 ; $i < 158 ; $i++)
{
$content .= fgets($file, 200);
if($i==65)
{
$content_array = file($filename);
print_r ($content."</br>");
}
}
fclose($file);
}
?>
我想顯示所需的行,然后使用這些行制作一個UPDATE TABLE。
我要獲取的行是txt文件中從57到65的行,但我無法僅獲取這些行。
<?php
$File = "file.txt"; // I assume your file has 57th and 65th line
$fhandle = fopen($File, 'r');
while(!feof($fhandle)) // until end of file
{
$data[] = fgets($fhandle); // place each line to array
//Do whatever you want with the data in here
//This feeds the file into an array line by line
}
fclose($fhandle);
echo "<pre>"; // makes output easier to read
print_r($data[56].$data[64]); // outputs 57th and 65th line
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.