@@ -312,11 +312,36 @@ function toJson(array $header=NULL) : string {
312312 * @return string
313313 */
314314 function toCsv (array $ header =NULL ) : string {
315+ $ parseHeader = [];
315316 $ parsedData = $ this ->toArray ($ header );
316317 $ csvData = '' ;
317318 if (!empty ($ parsedData )) {
318- if (!empty ($ this ->header )) {
319- $ csvData .= implode ($ this ->delimiter , $ this ->header ).PHP_EOL ;
319+ if (!empty ($ header )) {
320+ //Check header is valid or not
321+ if (!empty ($ this ->header )) {
322+ if ($ this ->ignoreHeaderCase == true ) {
323+ $ ignoreHeaderCase = array_map ('strtolower ' , $ this ->header );
324+ $ tmpHeader = array_combine ($ ignoreHeaderCase , $ this ->header );
325+ } else {
326+ $ tmpHeader = array_combine ($ this ->header , $ this ->header );
327+ }
328+ }
329+ //Parse header data
330+ foreach ($ header as $ col ) {
331+ $ tmpCol = $ col ;
332+ if ($ this ->ignoreHeaderCase == true ) {
333+ $ col = strtolower ($ col );
334+ }
335+ if (!array_key_exists ($ col , $ tmpHeader )) {
336+ //Throw error header not found
337+ throw new Exception ("Error: ' " .$ tmpCol ."' header not found " );
338+ } else {
339+ $ parseHeader [$ tmpCol ] = $ tmpHeader [$ col ];
340+ }
341+ }
342+ }
343+ if (!empty ($ parseHeader )) {
344+ $ csvData .= implode ($ this ->delimiter , $ parseHeader ).PHP_EOL ;
320345 }
321346 foreach ($ parsedData as $ row ) {
322347 $ csvData .= implode ($ this ->delimiter , $ row ).PHP_EOL ;
0 commit comments