2016-03-08 79 views
1

我很頭痛,想要弄明白這一點。無法通過類方法獲取csv

我的文件夾結構如下:

index.php 
helpers: 
    API.php 
    helpers.php 
assets: 
    products.csv 
debug: 
    debug_info.txt 

我的索引文件看起來如下:

<?php 
require_once 'helpers/API.php'; 
file_put_contents('debug/debug_info.txt', "New request started"); 
if (in_array($_GET['action'],array('insertOrder','updateOrder'))){ 
    $date = date(DATE_RFC2822); 
    $api = new API(); 
    file_put_contents('debug/debug_info.txt', "New: {$_GET['action']} at {$date}\n", FILE_APPEND | LOCK_EX); 
    file_put_contents('debug/debug_info.txt', "This is the product " . $api->getOrder()); 
} 

API.php

<?php 

class API { 
    private $order; 
    private $product_table; 

    function __construct(){ 
     $this->order = $this->setOrder(); 
     $this->product_table = $this->setProductTable(); 
    } 

    public function setOrder(){return $this->readJSON();} 
    public function setProductTable(){return $this->readProductsCSV(__DIR__ . '/../assets/products.csv');} 

    public function getOrder(){return $this->order;} 
    public function getProductsTable(){return $this->product_table;} 

    private function readJSON(){ 
     $stream = fopen('php://input', 'rb'); 
     $json = stream_get_contents($stream); 
     fclose($stream); 
     return print_r(json_decode($json, true), true); 
    } 

    private function readProductsCSV($csv = '', $delimiter = ','){ 
     if (!file_exists($csv) || !is_readable($csv)){ 
      return "Someone f*cked up -_-"; 
     } 

     $header = NULL; 
     $data = array(); 

     if (($handle = fopen($csv, 'r')) !== false){ 
      while (($row = fgetcsv($csv, 100, $delimiter)) !== false){ 
        if (!$header) 
         $header = $row; 

        else if($row[0] != ''){ 
         $row = array_merge(array_slice($row,0,2), array_filter(array_slice($row, 2))); 
         $sku = $row[0]; 
         $data[$sku]['productCode'] = $row[1]; 
         $data[$sku]['Description'] = $row[2]; 
        } 
      } 
      fclose($handle); 
     } 
     array_change_key_case($data, CASE_LOWER); 
     return print_r($data, true); 
    } 
} 

當我使用file_put_contents('debug/debug_info.txt', $api->getOrder());我得到數據正確(我必須評論所有的p roduct_table部件爲它工作)。

但無論我做什麼,我都無法獲取CSV文件。 我跑file_exists() && is_readable(他們通過)但仍然沒有。

如果我在index.php中聲明函數readProductsCSV,它可以工作..但它似乎使用它作爲一種方法來bug一切。

有人能幫我嗎?

回答

0

邏輯錯誤:

if (($handle = fopen($csv, 'r')) !== false){ 
      ^---your csv file handle 

     while (($row = fgetcsv($csv, 100, $delimiter)) !== false){ 
           ^---your csv filename, which SHOULD be the handle 

既然你試圖用一個字符串作爲文件句柄,你會得到一個布爾falsefgetcsv()失敗回首,那假終止while循環,$data保持空陣列。

+0

不錯,趕上!非常感謝,M8!我還必須將'public function setProductTable()'中的'return'從'return $ this-> readProductsCSV(__ DIR__。'/../ assets/products.csv')''更改爲'return $ this-> readProductsCSV $ csv = __DIR__。'/../ assets/products.csv')' – Onilol