Search code examples
phpcsvtext-parsing

How to parse semicolon-delimited lines of text in a csv file with fgetcsv()


I'm trying to read a CSV file and turn it into an array like this.

$h = fopen("onderdelen-test.csv", "r");

echo '$parts = array(';

if($h) {
    while (($data = fgetcsv($h, 1000)) !== FALSE) {
        foreach ($data as $num) {
            $part = explode(';', "$num");

            echo "array('partid' => '$part[0]', ";
            echo "'descr' => '$part[1]'), ";
        }
    }
    fclose($h);
}

echo ')';

The csv looks like this

123456 ; partdescription
234567 ; partdescription, anotherdescription
345678 ; part, description and some other description

The problem is that it also explodes on commas and not only on the semicolon. I've tried adding quotes around the description but did put some weird questionmarks around the description that I could not get rid of.

Edit 1: If I used the semicolon as delimiter in the fgetcsv function, then I can't retrieve the values by key, it just starts another loop everytime a semicolon is found.


Solution

  • Keeping it simple as all you are trying to do is see what is produced from this input before progressing on to bigger things

    123456 ; partdescription
    234567 ; partdescription, anotherdescription
    345678 ; part, description and some other description
    

    This code, note I have added the third parameter to the fgetcsv

    <?php
    $h = fopen("onderdelen-test.csv", "r");
    
    if($h) {
        while (($data = fgetcsv($h, 1000, ';')) !== FALSE) {
            print_r($data);
            echo "partid = " . trim($data[0]) . "\n";
            echo "descr  = " . trim($data[1]) . "\n";
        }
        fclose($h);
    }
    

    Produces this output

    Array
    (
        [0] => 123456
        [1] =>  partdescription
    )
    partid = 123456
    descr =  partdescription
    Array
    (
        [0] => 234567
        [1] =>  partdescription, anotherdescription
    )
    partid = 234567
    descr =  partdescription, anotherdescription
    Array
    (
        [0] => 345678
        [1] =>  part, description and some other description
    )
    partid = 345678
    descr =  part, description and some other description