在php中检索多个值的文本中的变量

时间:2013-01-29 14:36:39

标签: php text text-files

txt文件中的内容:

<test@test.com>: connect to test.com[00.00.00.0]:0: Connection timed out
recipient=test@test.com
offset=00000
status=0.0.0
action=delayed
reason=connect to test.com[00.00.00.0]:0: Connection timed out


<test234@test234.com>: connect to e-mail.com[00.00.00.0]:0: Connection timed out
recipient=test234@test234.com
offset=00000
status=0.0.0
action=delayed
reason=connect to test234.com[00.00.00.0]:0: Connection timed out

我需要在txt文件中输入变量: 例如:

$email =    test234@test234.com
$content = : connect to e-mail.com[00.00.00.0]:0: Connection timed out
             recipient=test234@test234.com
             offset=00000
             status=0.0.0
             action=delayed
             reason=connect to test234.com[00.00.00.0]:0: Connection timed out

我尝试但不工作

<?php 
$connect = mysql_connect('localhost','root','');
if(!$connect)
{
  die('Could not connect:' . mysql_error());
}
mysql_select_db('test',$connect);


// txt file

$file = fopen("email_errors.txt", "r") or exit ("Unable to open file");

while ( ($line = fgets($file)) !== false) {

   // get the email <email@email.com>
   preg_match_all('/\<(.+)\>/', $line, $coincidencias);

foreach ($coincidencias[1] AS $email) 
{
   // create a query and insert into database
    $sql = "INSERT INTO errormailer(id_error, email, description, fecha)    VALUES(NULL,'".$email."',' $description (the description)',now());";

    echo '<pre>'.$sql. '</pre>';
    mysql_query($sql);
}
}

我无法找到正确的方法 我需要将它们放入变量中以便存储在数据库中。

1 个答案:

答案 0 :(得分:0)

$connect = mysql_connect('localhost','root','');
if(!$connect)
{
  die('Could not connect:' . mysql_error());
}
mysql_select_db('test',$connect);


// txt file

$file = fopen("email_errors.txt", "r") or exit ("Unable to open file");

$i = 0;

while ( ($line = fgets($file)) !== false) {

   // get the email <email@email.com>
   if (preg_match('/\<(.+)\>/', $line, $email)) {
     $coincidencias[] = $email[1];  
   }
   if (strlen(trim($line)) > 0) {
        $still_empty = false;
        $content[$i] .= preg_replace('/\<.+\>: /', '', $line);
   } else {
       if (!$still_empty) {
            $i++;   
       }
       $still_empty = true; 
   }
}

$i = 0;
foreach ($coincidencias as $email) 
{
    // create a query and insert into database
    $sql = "INSERT INTO errormailer(id_error, email, description, fecha) VALUES(NULL,'".$email."','".$content[$i]."',now());";
    echo '<pre>'.$sql.'</pre>';
    $i++;
    mysql_query($sql);
}