Forum

Thread tagged as: Question, Api

Adding content from .csv file

I've been reading up on the docs about how to import content from an external source, specifically with regards to Products: https://docs.grabaperch.com/api/import/shop/products/

There seems to be a gap in the instructions when it comes to linking the actual data source, looping through it and specifying the content from rows within the .csv file. Could you provide some instruction as to how this works please?

Rob Saunders

Rob Saunders 0 points

  • 3 years ago

Hi Rob

It's basically up to however you write the app in php – there is no prescribed way to do this.

You can use the fopen and fgetcsv functions to open a file and read through the results adding them to an array. Map the fields in your collection/products to the data array rather than the fixed test data shown in the example.

NB 100 counter being the limit which you could then add a pause to in order to ease the hit on the server if you needed to.

try {

    if (($handle = fopen("data.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 100, ",")) !== FALSE) {

        $result =  $Importer->add_item([
        'field 1'    => $data[0],
        'field 2'    => $data[1],
        etc, etc
    ]); 

    }
    fclose($handle);

    echo('Done!');
}    

} catch (Exception $e) {
    die('Error: '.$e->getMessage());
}

Jonathan thats brill, thank you for pointing me in the right direction, I though this was something that perch would be handling rather than php, thats great to know. This would be a very helpful example to have in the documentation.