/** * Tests PFXUtils::arrayToCSV(). */ public function testArrayToCSV() { $expected = <<<EOF Foo,Bar,Baz hello,my,friend how,are,you today,, EOF; $input = array(array('Foo', 'Bar', 'Baz'), array('hello', 'my', 'friend'), array('how', 'are', 'you'), array('today', null, null)); $this->assertEquals($expected, PFXUtils::arrayToCSV($input)); // Change up the delimiter $expected = str_replace(',', ';', $expected); $this->assertEquals($expected, PFXUtils::arrayToCSV($input, ';')); /* A formatted line should contain one fewer delimiters than elements in the corresponding array. */ $expected = <<<EOF Foo,Bar,Baz hello,my,friend how,are,you today? I,am,fine. EOF; $input = array(array('Foo', 'Bar', 'Baz'), array('hello', 'my', 'friend'), array('how', 'are', 'you'), array('today?'), array('I', 'am', 'fine.')); $this->assertEquals($expected, PFXUtils::arrayToCSV($input)); // Again, with a different delimiter $expected = str_replace(',', '&', $expected); $this->assertEquals($expected, PFXUtils::arrayToCSV($input, '&')); // Delimiters or EOL characters embedded in data should trigger quoting $expected = <<<EOF 1,"2,3",4,5 a,b,"c, d", e,f EOF . "\"two\nlines\"," . <<<EOF 2.356 foo,bar,baz, EOF . "\"flarf\r\n\""; $input = array(array(1, '2,3', 4, 5), array('a', 'b', 'c, d', ' e', 'f '), array("two\nlines", 2.356), array('foo', 'bar', 'baz', "flarf\r\n")); $this->assertEquals($expected, PFXUtils::arrayToCSV($input)); /* If data is quoted due to the presence of delimiters, embedded quotes should be doubled. */ $expected = <<<EOF Foo ;Bar ;Baz 12";5',10";"7';9""" a;b;c EOF; $input = array(array('Foo ', 'Bar ', 'Baz '), array('12"', '5\',10"', '7\';9"'), array('a', 'b', 'c')); $this->assertEquals($expected, PFXUtils::arrayToCSV($input, ';')); // How about tabs? $expected = "Foo\tBar\n1\t2\t3\na,b\t\"c\t\""; $input = array(array('Foo', 'Bar'), array(1, 2, 3), array('a,b', "c\t")); $this->assertEquals($expected, PFXUtils::arrayToCSV($input, "\t")); }