Since the fputcsv() function is designed to output its result to a file, I came up with this little solution for a case where I wanted to write it to a string variable (for use in an error message). Thought it might be useful to post here in case anyone else ever needs to do something similar:

	private function writeArrayToCsvStr(Array $arr)
	{
		if(($fh = fopen('php://temp', 'rw')) == false) {
			throw new Exception("Unable to fopen php://temp");
		}
		// might want validation here that it's a 1-D array?
		$result = fputcsv($fh, $arr);
		rewind($fh);
		$result = fread($fh, 9999);
		fclose($fh);
		return $result;
	}

    I can't find it now, but I swear that was an example somewhere (I'm thinking I first saw Weedpacket use it) where you could create a stream context that allowed you to create an I/O resource for the contents of a variable. In other words, fputcsv() on that resource would write the data directly into the contents of the variable.

      That's right; it's not mine - you'll find it as the working example used for describing the stream interface.

        Ah, you mean [man]stream.streamwrapper.example-1[/man]? Hm... shame, that's definitely not as concise as writing/reading using php://temp.

          True: but you can have more than one (should that be necessary for some reason), and reading is really simple - if you don't mind global variables.

          I mean, I've never used it as-is (like any example code it's more proof-of-concept than the real thing), but I have used it as an outline of a design sketch.

            Write a Reply...