简体   繁体   English

PHP将文本文件中的解析值插入MySQL DB

[英]PHP inserting parsed values from text file into MySQL DB

I'm new to PHP and am trying to parse certain text from a txt file, and then insert the text into a MySQL database. 我是PHP的新手,正在尝试从txt文件解析某些文本,然后将文本插入MySQL数据库。 So, let's get more specific. 因此,让我们更具体一些。 The file's format is as such, and it is repeated through the document end. 文件的格式是这样,并且在文档末尾重复该格式。 the ellipses represent the previous and next tones. 椭圆代表前一个和下一个音调。

...

[Tone27]                            
Atone = 707.3                        
Btone = 746.8                        
Btonelength = 3                        
Btonedebounce = 1                    
Description = Fire Department 1                
mp3_Emails = email@address.com,email2@address.com,email3@address.com          
amr_Emails = email2@textmessaging.com,email1@textmessaging.com        
alert_command = c:\test.bat                
post_email_command = c:\test2.bat            
radio_frequency = 154.475    
exclude_from = 13:25                        
exclude_to = 13:35                        
exclude_emails = email2@textmessaging.com,email2@address.com

... 

What I want to do is parse the first items(eg '[tone27]') in each "tone block" from the file and insert it into the first field of a NEW row in the db. 我想做的是从文件中解析每个“音调块”中的第一项(例如“ [tone27]”),并将其插入数据库中NEW行的第一个字段中。 I then need to evaluate what comes before each line's " = ", for instance "Atone," and insert what comes after that line's " = ", for instance "707.3" into a field by that name. 然后,我需要评估每行“ =”之前的内容(例如“ Atone”),并将该行“ =”之后的内容(例如“ 707.3”)插入该名称的字段中。 so, this row may look like this in the db: 因此,该行在数据库中可能如下所示:

$id | [tone27] | 707.3 |746.8 | 3 | 1 | Fire Department 1 |email1@x.com,email2@x.com,e...|...

and so on... 等等...

i've been able to isolate each thing by performing string functions, but am unsure of how to set up a loop that would insert each value properly. 我已经能够通过执行字符串函数来隔离每件事,但是不确定如何设置一个循环来正确插入每个值。 Here's the code I used to isolate them, but it's not helping at all with actually getting them into the database. 这是我用来隔离它们的代码,但是将它们真正放入数据库中完全没有帮助。

$txt_file    = file_get_contents('config/tones.txt');
$rows        = explode("\n", $txt_file);
foreach($rows as $row => $data)
{   
$row_data = explode(' = ', $data);

if ((isset($row_data[0])) && ($row_data[0] !== " " )){
    $info[$row]['attribute'] = $row_data[0];
    $info_attribute = trim($info[$row]['attribute']);
}
if (isset($row_data[1])){
    $info[$row]['value']         = $row_data[1];
    $info_value = trim($info[$row]['value']);
    //display data
    echo 'Row ' . $row . ' Attribute: ' . $info_attribute . '<br />';
    echo 'Row ' . $row . ' Value: ' . $info_value . '<br />';
} elseif (($info[$row]['attribute']) && (!empty($info_attribute))) {
    echo "<br>";
    echo 'Row ' . $row . ' Attribute: ' . $info_attribute . '<br />';
    continue;
}      

I'M A NOOB, NO DOUBT. 我是新手,没有疑问。 I'M LOST. 我迷路了。 Thanks in advance for your help!!! 在此先感谢您的帮助!!!

****|| EDIT ||****

Thanks for all of the excellent answers! 感谢所有出色的答案! here's what I've resultingly come up with. 这就是我最终想出的。 No queries yet, just a simple dash of the read portion of CRUD, but the code will be the same, only with queries. 尚无查询,只是CRUD读取部分的一小部分,但代码将是相同的,只是带有查询。 A big thanks to @leepowers for introducing me to the wonderful parse_ini_file() function. 非常感谢@leepowers向我介绍了出色的parse_ini_file()函数。

foreach(parse_ini_file("config/tones.txt", true) as $k => $v){
extract($v, EXTR_SKIP);
echo "<br>";
echo $k . "<br>"; 
foreach($v as $sv => $ssv){ 

    $lcase_sv = strtolower($sv); 
    if (trim($lcase_sv) == 'amr_emails'){ 
        echo "sv: amr_Emails:<br>"; 
        echo "ssv:<br>";
        $eA = explode(',', trim($ssv));
        foreach($eA as $eK => $eV){ 
            echo "email" . filter_var($eK + 1, FILTER_SANITIZE_NUMBER_INT) . ": " . $eV . "<br>"; 
        }
    } elseif (trim($lcase_sv) == 'mp3_emails'){ 
        echo "ssv:<br>";
        $eA = explode(',', trim($ssv));
        foreach($eA as $eK => $eV){
            echo "email" . filter_var($eK + 1, FILTER_SANITIZE_NUMBER_INT) . ": " . $eV . "<br>";
        }
    }else {
        echo "sv: " . $sv .", " . "s: " . $ssv . "<br>"; 
    }
}

} }

parse_ini_file($source); parse_ini_file($ source); return an associative array 返回一个关联数组

$query = 'INSET INTO ... (key, value) VALUES (:key, :value)';
$stmt  = DB::prepare($query);

foreach( parse_ini_file($source) as $key => $value )
{
  $stmt->execute(array(':key' => $key, ':source' => $source));
}

This example use PDO 本示例使用PDO

Just output of file in loop is: 循环中文件的输出仅为:

foreach( parse_ini_file($source) as $key => $value )
{
  echo $key; // Atone in first loop
  echo $value; //707.3 in first loop

  // BUT NOT USE THIS!!! use mysqli or PDO
  mysql_query("INSERT INTO ... (key, value) VALUES ($key, $value)");
}

Use parse_ini_file to load the data structure into an array. 使用parse_ini_file将数据结构加载到数组中。

From there you can build and execute SQL statements: 从那里您可以构建和执行SQL语句:

$entries = parse_ini_file("config/tones.txt", true);
foreach ($entries as $section => $fields) {
  extract($fields, EXTR_SKIP);
  $sql = "INSERT INTO mytable (section, atone, btone) VALUES ($section, '$Atone', '$Btone'";
   ....
}

Of course, you'll need to prepare and escape the SQL statement before executing it. 当然,在执行该语句之前,您需要准备并转义该SQL语句。

Here's another way to do it. 这是另一种方法。 Just need to modify it according to you needs (number of rows/credentials). 只需根据需要进行修改(行数/凭证)。 It's better to use PDO. 最好使用PDO。

$username = 'yourusername';
$password = 'yourpass';

try {
    $conn = new PDO('mysql:host=127.0.0.1;dbname=yourdbname', $username, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo 'successfully connected';
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

foreach(parse_ini_file('yourfile.ini', true) as $row)
{
    try {
        // just adjust the number of columns accordingly
        $stmt = $conn->prepare('insert into tablename values(?,?,?,?,?,?,?,?,?,?,?,?,?)');
        // $row contains the values to insert
        $stmt->execute($row);
        echo 'rows affected' . $stmt->rowCount(); // 1      
    }catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM