0

I have stored CSV files in a local folder. And i am displaying the names of the files in the local folder in the form of a list on the frontend dynamically.

FILE NAME LISTING

$path = "uploads/";
$files = scandir($path);
foreach($files as $file) {
    if ($file[0] != '.') $nothidden[] = $file;
}

for ($x=0;$x<count($nothidden);$x++){
    ?><li class="active"><a><?php ${'file'.$x} = $nothidden[$x]; echo $nothidden[$x]; ?></a></li><br/>
    <?php
}

I am able to display the csv file in tabular form one at a time statically.

CSV FILE TABLE

$value = 'file.csv';
$target='uploads/'.basename($value);
echo "<table id='toggle-vis'>\n\n";
  $f = fopen($target, "r");
  while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                 echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
  }
  fclose($f);
  echo "\n</table>"

What i want is to display is the table of a csv file from the local directory when clicked on the particular name of the file in the list displayed. And when the other file name on the list is clicked, the previous table should be removed and the data from the clicked file should populate the table. Any help please?

8
  • You will need to use ajax to send the request and php to process the request, read the file and return the data from the csv file Commented Nov 1, 2017 at 7:58
  • you mean to say to clicking on csv it will list contents of csv right Commented Nov 1, 2017 at 7:59
  • @RamRaider could you explain how exactly to do that, i tried some code with it, but ultimately i was getting stuck. Commented Nov 1, 2017 at 8:03
  • @Dipakchavda yes, clicking on the csv file name listed. Commented Nov 1, 2017 at 8:04
  • If you post the code you tried and explain where you "got stuck" then we can have a look at it and suggest possibilities Commented Nov 1, 2017 at 8:07

2 Answers 2

0

This is a very quickly written example - it works for me as a test but you will need to look at it carefully to make suitable edits to suit your final needs and environment.

The ajax function is invoked when an a within the list is clicked. The code looks at the event and uses the event.target to intercept the innerHTML for the a - that is the filename sent as a parameter ( via ajax ) to the php script. The PHP script checks that the method is POST and that there is a filename in the POST array - if it is OK then will process that file and send back the csv data. This could be edited so that only the filename rather than the full filepath is sent so that users do not know the actual filepaths used on your system!

<?php
        if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['filename'] ) ){

            $filename=filter_input( INPUT_POST, 'filename', FILTER_SANITIZE_STRING );

            if( $filename && realpath( $filename ) ){
                ob_clean();

                $hndl=fopen( $filename, 'r' );
                $html=array();

                $html[]="<table id='toggle-vis'>";
                while ( ( $line = fgetcsv( $hndl ) ) !== false ){
                    $html[]="<tr>";
                    foreach( $line as $cell )$html[]="<td>$cell</td>";
                    $html[]="</tr>";
                }
                $html[]="</table>";

                fclose( $hndl );

                header( 'Content-Type: text/html' );
                exit( implode( PHP_EOL, $html ) );
            }
        }
?>
<!doctype html>
<html>
    <head>
        <title>csv manipulations</title>
        <script>
            /*
                basic ajax function
            */
            function ajax(m,u,p,c,o){
                /*
                    Method,Url,Params,Callback,Options
                */
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };

                var params=[];
                for( var n in p )params.push( n+'='+p[ n ] );

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }

                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }

            /*
                event handler assigned to each `a` within the list ( li.active > a )
            */
            function getcsvdata(e){
                try{
                    e.preventDefault();

                    var method='post';
                    var url=location.href;
                    var params={
                        filename:e.target.innerHTML
                    };
                    var callback=csvcallback;
                    var options={};

                    ajax.call( this, method, url, params, callback, options );

                }catch( err ){
                    console.warn( err );
                }
            }

            /*
                ajax callback to process the response from the php script at the top
            */
            function csvcallback( data ){
                try{

                    var table=document.getElementById('toggle-vis');
                    if( table ){
                        var parent=table.parentNode;
                        parent.removeChild( table );

                        parent.insertAdjacentHTML('beforeend',data);
                    }
                }catch( err ){
                    console.warn( err );
                }
            }


            /*
                Bind event handlers to each `a` in list 
            */
            document.addEventListener('DOMContentLoaded',function(){
                var col=Array.prototype.slice.call( document.querySelectorAll('li.active > a') );
                col.forEach(function(e){
                    e.addEventListener('click',getcsvdata,false);
                });
            }, false );
        </script>
    </head>
    <body>
        <h1>CSV Files</h1>
        <ul id='list'>
        <?php

            /* edit to suit */
            $dir='c:/temp2/csvfiles';


            $col=glob( $dir . '/*.csv' );
            if( !empty( $col ) ){
                foreach( $col as $file ){
                    echo "<li class='active'><a href='#'>$file</a></li>";
                }
            }
        ?>
        </ul>
        <table id='toggle-vis'>
            <tr>
                <td>csv data to appear here when links clicked</td>
            </tr>
        </table>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

1 Comment

you, my sir are Houdini. Thank you !
0

Following the piece of code may help to you.

var csvData;
$(document).ready(function() {
    $("#btnGET").click(function() {
        csvData = $.ajax({
            type: "GET",
            url: "<csv file path>",
            dataType: "text/csv",
            success: function (result) {
                alert(result);
                alert("done!"+ csvData.getAllResponseHeaders())
            }
        });
    });
});

1 Comment

Thank you, it'll be of great help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.