Ability to set custom headers (whether or not headers exist in the file) #103
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
If you read a CSV file which does not contain a header row, you will use
noHeaderRow()
, which returns each data row with integer keys.For example, this file:
will be returned as:
However, if you already know what the headers should be for the file (i.e. they are defined externally), it would be nice to be able to get each data row with the correct headers.
For example, you know the headers should be
email
,first_name
andlast_name
, so you want the above file to be returned as:In order to do this currently, you would need to reimplement all the array_slice/array_combine logic from
getValueFromRow()
in your own code.To support this, I have added a
setHeaders(array $headers)
method, where you can specify the custom headers to use. It affects the output ofgetValueFromRow()
and thereforegetRows()
, so that the custom headers are used instead of integer keys.It can either be used with
noHeaderRow()
(custom headers will be used instead of integer keys), or without (custom headers will be used instead of the headers defined in the file, and the header row will not be returned as a data row). It is also compatible withheaderOnRow()
(previous rows will be skipped, and custom headers will be used instead of headers defined in the file).It also affects the output of
getHeaders()
by returning only the custom headers you have defined, so the newgetOriginalHeaders()
method can be used to get the header row actually defined in the file, if required.