无法使用类方法获取 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());
}

原料药.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());时,我正确获取了数据(我必须注释所有product_table部分才能使其正常工作)。

但是无论我做什么,我都无法获得CSV文件。我已经跑了file_exists() && is_readable(他们通过了),但仍然一无所获。

如果我在index.php中声明函数readProductsCSV,它可以工作..但似乎将其用作方法会错误一切。

有人可以帮我吗?

逻辑错误:

    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

由于您尝试使用字符串作为文件句柄,因此您会从失败的fgetcsv()中返回一个布尔false,该 false 终止while循环,并且$data保持为空数组。

最新更新