Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

csv - Is there a way to access a string as a filehandle in php?

I'm on a server where I'm limited to PHP 5.2.6 which means str_getcsv is not available to me. I'm using, instead fgetcsv which requires "A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen()." to operate on.

My question is this: is there a way to access a string as a file handle?

My other option is to write the string out to a text file and then access it via fopen() and then use fgetcsv, but I'm hoping there's a way to do this directly, like in perl.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you take a look in the user notes on the manual page for str_getcsv, you'll find this note from daniel, which proposes this function (quoting) :

<?php
if (!function_exists('str_getcsv')) {
    function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "") {
        $fiveMBs = 5 * 1024 * 1024;
        $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
        fputs($fp, $input);
        rewind($fp);

        $data = fgetcsv($fp, 1000, $delimiter, $enclosure); //  $escape only got added in 5.3.0

        fclose($fp);
        return $data;
    }
}
?>

It seems to be doing exactly what you asked for : it uses a stream, which points to a temporary filehandle in memory, to use fgetcsv on it.


See PHP input/output streams for the documentation about, amongst others, the php://temp stream wrapper.


Of course, you should test that it works OK for you -- but, at least, this should give you an idea of how to achieve this ;-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...