Custom admin plugin read CSV

admin2025-06-06  2

I've made a plugin in admin, very simple. I just need to read a CSV files, put data into an array.

I use this :

$csv = array();

    if (($file = fopen('my-file.csv', 'r')) === false){
        echo 'There was an error loading the CSV file.';
    }else{
        while (($line = fgetcsv($file, 1000)) !== false){
            $csv[] = $line;
        }
        fclose($handle);
    }

I found this function on web, it works when I use it in a single php file on my local server (outside of wordpress).

The problem is I can't read the file. I put the file in the plugin directory.

I tried with many ways to link url but no one work.

Anyone know how I can read the file?

I've made a plugin in admin, very simple. I just need to read a CSV files, put data into an array.

I use this :

$csv = array();

    if (($file = fopen('my-file.csv', 'r')) === false){
        echo 'There was an error loading the CSV file.';
    }else{
        while (($line = fgetcsv($file, 1000)) !== false){
            $csv[] = $line;
        }
        fclose($handle);
    }

I found this function on web, it works when I use it in a single php file on my local server (outside of wordpress).

The problem is I can't read the file. I put the file in the plugin directory.

I tried with many ways to link url but no one work.

Anyone know how I can read the file?

Share Improve this question asked Nov 23, 2018 at 16:11 Jérémie CzkJérémie Czk 32 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 0

$_SERVER['DOCUMENT_ROOT'] should get you taken care of. Check this out:

<?php

echo 'Initializing Script...<br>';

$filepath = $_SERVER['DOCUMENT_ROOT']."/data/clients.csv";

echo "the file we seek:".$filepath."<br>";

$handle = fopen($filepath, "r") or die("Error opening file");

$i = 0;

while(($line = fgetcsv($handle)) !== FALSE) {
    if($i == 0) {
        $c = 0;
        foreach($line as $col) {
            $cols[$c] = $col;
            $c++;
        }
    } else if($i > 0) {
        $c = 0;
        foreach($line as $col) {
            $client_data[$i][$cols[$c]] = $col;
            $c++;
        }
    }
    $i++;
}
fclose($handle);
echo "inital loop good<br>";
echo "<pre>";

foreach ($client_data as $client_row){
    $data = $client_row['column_header_label'];
    //do whatever       
    }
?>
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749155539a316837.html

最新回复(0)