Fatal error: Uncaught Error: Call to a member function format() on bool on line 58

1k Views Asked by At

I must retrieve data from a CSV file and to show the month and year from a date written in string format.I run the code and it shows the A non well formed numeric value encountered error.I also tried other ways to convert the date and I get the year 1900 for each date.

use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
require('php_library/spreadsheet-reader-master/php-excel-reader/excel_reader2.php');

require('php_library/spreadsheet-reader-master/SpreadsheetReader.php');


if(isset($_FILES["filename"]))
{
 $file = $_FILES["filename"]["tmp_name"];
 $file_open = fopen($file,"r");
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
$spreadsheet = $reader->load($file);
$sheetData = $spreadsheet->getActiveSheet()->toArray();
 foreach ($sheetData as $i=>$Row)
    {
        foreach($Row as $j=>$column)
        {
            // echo $Row[$j].", ";
            if($i == 0)
            {
            if($Row[$j] == "Codice cliente")
                $column1 = $j;
            if($Row[$j] == "Data emissione")
            {
                $column2 = $j;
                // echo $j;
            }
        }
            
        }
      

    }
foreach ($sheetData as $i=>$row)

    {  
        if($i!=0){
      json_encode(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[$column2])->format('Y'));
}

enter image description here

1

There are 1 best solutions below

1
On

I guess this is the offending line in your code; it's the only line using a ->format() method.

json_encode(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[$column2])->format('Y'));

Let's try breaking it into multiple lines so it's readable.

$excelDatestamp = $row[$column2];
$dto = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject( $excelDatestamp ); 
$year = $dto->format( 'Y' );
json_encode( $year );

It seems likely to me that the $excelDatestamp generated by this refactoring of your code is malformed. That makes ::excelToDateTimeObject() return false, letting you know you have an error. Then you try to invoke the format method like this (false)->format( 'Y' ). That's why php threw the error message you showed us.

And, you don't do anything with the output of json_encode() so even if everything worked it would get lost.