skip to Main Content

I have an issue I cannot seem to fix. I have a function that takes a file and converts it to an array using the first row as the keys:

function parseCSVToArray($filePath)
{
    $csvData = [];

    if (($handle = fopen($filePath, "r")) !== false) {
        $keys = fgetcsv($handle); // Get the first row as keys

        while (($data = fgetcsv($handle)) !== false) {
            $rowData = array();
            foreach ($keys as $index => $key) {
                $rowData[$key] = $data[$index] ?? ''; // Assign each value to its corresponding key
            }
            $csvData[] = $rowData;
        }

        fclose($handle);
    }
    return $csvData;
}

Everything works as normal and creates the array as expected:

$getTheRecords = parseCSVToArray('Data/records.csv');

// File contents
record,subdomain,hub_knows,domain,type,value,action,rationale
mail.sub.domain.com.,sub.domain.com,Hub knows about this,domain.com,CNAME,dispatch.domain.com.,DELETE,Dispatch links can go
Array
(
    [record] => mail.sub.domain.com
    [subdomain] => sub.domain.com
    [hub_knows] => Hub knows about this
    [domain] => domain.com
    [type] => CNAME
    [value] => dispatch.domain.com.
    [action] => DELETE
    [rationale] => Dispatch links can go
)

Now the issue is when I go to use or print the data. When I loop through the array using:

foreach($getTheRecords as $element)
{
    echo "<div style='margin-bottom: 20px'>";
    echo($element['subdomain']); // This will print the subdomain as expected.
    echo "</div>";
}

If I change ‘subdomain’ to ‘record’ it prints nothing. However, every other ‘key’ prints the results just fine.

Thank you in advance for your help!

I have tried changing the name of the first key to ‘mainrecord’ or anything and it still will not print out.

Iside loop var_dmup():

array(8) {
  ["record"]=>
  string(31) "mail.0lemonade.starchapter.com."
  ["subdomain"]=>
  string(25) "0lemonade.starchapter.com"
  ["hub_knows"]=>
  string(20) "Hub knows about this"
  ["domain"]=>
  string(17) "scdomaintest3.com"
  ["type"]=>
  string(5) "CNAME"
  ["value"]=>
  string(22) "dispatch.scnetops.com."
  ["action"]=>
  string(6) "DELETE"
  ["rationale"]=>
  string(21) "Dispatch links can go"
}

2

Answers


  1. To troubleshoot this issue, you can try the following steps:

    Check the CSV file: Open the CSV file in a text editor and inspect the value of the "record" key in the first row. Make sure there are no extra spaces or invisible characters.

    Trim the key: Modify the code inside the foreach loop to trim the key before assigning it to the $rowData array. This ensures that any leading or trailing white spaces are removed.

    Replace this line:

    $rowData[$key] = $data[$index] ?? ”;
    with:

    $rowData[trim($key)] = $data[$index] ?? ”;
    Debug the array: After parsing the CSV data into the $csvData array, you can add a print_r($csvData) statement to inspect the contents of the array. This will help verify if the "record" key is correctly stored in the array.

    // After the while loop ends, add this line
    print_r($csvData);
    Check the output and ensure that the "record" key exists with the expected value.

    By following these steps, you should be able to identify any discrepancies in the CSV file or the array structure that may be causing the issue.

    Login or Signup to reply.
  2. Your file likely has a UTF8 Byte Order Mark [BOM] at the beginning which is throwing off the first key. While a BOM isn’t necessary at all for UTF8, some programs still add it as a "hint" that the file is UTF8.

    If you var_dump($keys[0], bin2hex($keys[0]) you’ll likely see that the first key’s is longer than what is visible, and the hex output will show it prefixed with EFBBBF which is the BOM.

    Try replacing:

    $keys = fgetcsv($handle);
    

    With:

    $keys = str_getcsv(preg_replace("/^xefxbbxbf/", "", fgets($handle))); 
    

    Which will trim off the BOM, if it exists.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search