-3

假设我有如下 PHP 函数:

函数.php

<?php
function getDataInFile($PMTA_FILE){
    $PMTA_DATE = date("Y-m-d");
    $lineFromText = explode("\n", $PMTA_FILE);
    $number_bar_charts = 13;
    $row = 0;
    $cate = "";
    $total ="";
    $fail = "";
    $mailSuc = "";
    $title = "";
       foreach($lineFromText as $line){
            if($row < $number_bar_charts){
              $words = explode(";",$line);
              $dateTime .= ','.$words[0];
                if($title == ""){
                   $title = $words[0];
                }
                $cate .= ','."'$words[5]'";
                $total .= ','.$words[6];
                $fail .= ','.$words[7];
                $mailSuc .= ','.((int)$words[6] - (int)$words[7]);                          
            $row++;
      }   
     }

}


?>

这是下面的代码,我调用该函数在getFile.php.

<?php 
include("include/function.php");
$PMTA_DATE = date("Y-m-d");
getDataInFile("../stats_domain_recepteur.affinitead.net.".$PMTA_DATE.".txt");

?>

实际上,它无法从文件中读取数据,我收到了错误消息Undefined variable: dateTime in C:\wamp\www\chat\include\function.php on line 15Notice: Undefined offset: 5 in C:\wamp\www\chat\include\function.php on line 19....

我不知道如何解决这个问题,请任何人帮助我,谢谢。

4

3 回答 3

0

这些只是通知。它们并不是会破坏您的代码的可怕错误,但一些代码审查员会让您修复它们。PHP 只是给你一个礼貌的推动,但无论如何都会起作用。致命错误是会阻止 PHP 走上正轨的大而糟糕的问题。

以下是 PHP 发现的问题...

  1. You're appending data to the string $dateTime on each iteration. On the first pass through the variable doesn't yet exist. PHP doesn't really care, but will issue a warning. To get rid of that problem, define $dateTime before you use it.

    $dateTime = null;

  2. The second problem is an array out of bounds exception. You are trying to do something with $words[5] when that array index doesn't exist. In general, you should check that array indexes, variables and other fun stuff actually exist before you try to use them.

    $cate .= sprintf(",'%s'", isset($word[5]) ? $word[5] : '');

If you don't want to see Notices and Warnings reported in the error log, see PHP Error Handling to learn how to set which error levels you want to see in your log.

You should also read all about the file_get_contents function to actually get the file in the first place!

于 2012-12-14T05:02:30.073 回答
0

add $dateTime = ''; before foreach($lineFromText as $line){

this will works fine.

于 2012-12-14T05:03:01.500 回答
0

The error messages are 100% legit: you're trying to use a variable which hasn't been initialized before. Put this code above the loop and you'll get rid of this error:

$dateTime = '';

Regarding the second error - it tells that you don't have 6-th element in the array, so you'd better replace that code with a check:

$cate .= sprintf(",'%s'", isset($word[5]) ? $word[5] : '');

Extrapolate this check to other index accesses, as well.

于 2012-12-14T05:04:29.887 回答