2014-11-28 4 views
0

Я строю систему загрузки файлов и очищаю свой код. Я погружаюсь в OOP PHP. Вот мой код нижеPHP OOP File Handler не получает данные

<?php 
    //class fileData manipulates files and pulls thier data 
    class fileData{ 

     //global file variable 
     protected $file = null; 
     //global file handler 
     protected $handle = null; 
     //global file data object array 
     protected $fileData = array(); 

     //default constructor to initialize the class and return the file object 
     public function __construct($file){ 
      $this->file = $file; 
      $this->openFile(); 
     } 

     //open the file and return the handler. returns resource if successful, false if failed 
     private function openFile(){ 
       $this->handle = fopen($this->$file, 'r'); 
     } 


     //get the data from the file and set it as an object 
     public function getFileData(){ 
      //check the file handler 
      if(!$this->handle) 
       exit("Unable to open the file"); //if the file does not open exit the script 


      $headers = array(); //set the column titles in an array for the objecy attribute name 
      $row = 1; //set the row count 
      while(($data = fgetcsv($this->handle, 0, ',')) !== false){ 
       //if it is the first row get the column titles 
       if($row == 1){ 
        for($i = 0; count($data); $i++){ 
         //object attribute names array 
         array_push($headers, $data[$i]); 
        } 
       }else{ 
        //build the object array 
        $object = array(); 
        for($j = 0; count($headers); $j++){ 
         $object[$headers[$j]] = $data[$j]; 
        } 
        array_push($this->fileData, $object); 
       } 
       $row++; 
      } 
      //return the object array 
      return $this->fileData; 
     } 
    } 
?> 

Тогда на стороне HTML у меня есть следующий код

<?php 
require_once 'assets/server/upload/fileData.class.php'; 
if($_POST){ 
     if(isset($_FILES)){ 
      $fileData = new fileData($_FILES['spreadsheet']['tmp_name']); 
      print_r($fileData->getFileData()); 
     } 
    } 
?> 
<html> 
    <form action="" class="navbar-form navbar-left" method="post" enctype='multipart/form-data'> 
     <div class="form-group"> 
      <input type='file' class='form-control' name='spreadsheet'> 
     </div>      
     <input type='submit' class="btn btn-success" value='Upload file'> 
    </form> 
</html> 

Я имею функцию print_r только для тестирования, чтобы убедиться, что все распечатки в порядке, но я не являюсь получая любые данные после отправки формы. Любые мысли о том, почему это происходит и как это исправить?

ответ

2

В вашем предложении

while ($data = fgetcsv($this->handle, 0, ',') !== false) 

вы назначаете $data простой булево. Вы не получите ожидаемый массив. Должно быть:

while (($data = fgetcsv($this->handle, 0, ',')) !== false) 
+0

Я установил, что, и снова побежал он все еще не получить ничего –

+0

I не вижу других проблем в коде, который вы опубликовали. – clapas

1

После прекрасного совместных усилий с некоторыми членами для сообщества это окончательный результат, который мы придумали

<?php 
    error_reporting(E_ALL); 
    ini_set('display_errors', 1); 
    //class fileData manipulates files and pulls thier data 
    class fileData{ 
     //global file variable 
     protected $file = null; 
     //global file handler 
     protected $handle = null; 
     //global file data object array 
     protected $fileData = array(); 

     //default constructor to initialize the class and return the file object 
     public function __construct($file){ 
      $this->file = $file; 
      $this->openFile(); 
     } 

     //open the file and return the handler. returns resource if successful, false if failed 
     private function openFile(){ 
       $this->handle = fopen($this->file, 'r'); //corrected the syntax thank you -Fred -ii- 
     } 


     //get the data from the file and set it as an object 
     public function getFileData(){ 
      //check the file handler 
      if(!$this->handle) 
       exit("Unable to open the file"); //if the file does not open exit the script 
      $headers = array(); //set the column titles in an array for the objecy attribute name 
      $row = 1; //set the row count 
      //make sure data is being set to this proper array, thank you clapas for your input 
      while(($data = fgetcsv($this->handle, 0, ',')) !== false){ 
       //if it is the first row get the column titles 
       if($data[0] === "---") 
        break; 
       if($row == 1){ 
        for($i = 0; $i < count($data); $i++){ 
         //object attribute names array 
         array_push($headers, $data[$i]); 
        } 
       }else{ 
        //build the object array 
        $object = array(); 
        for($j = 0; $j < count($data); $j++){ 
         $object[$headers[$j]] = $data[$j]; 
        } 
        array_push($this->fileData, $object); 
       } 
       $row++; 
      } 
      //return the object array 
      return $this->fileData; 
     } 
    } 
?> 
+0

Я человек моих слов +1 и спасибо за упоминание. –

+0

Рок на! Скоро увидимся! –

+0

Всегда приятно Марк, * ура * –

Смежные вопросы