dracoblue.net

Generating/Parsing csv files with craur

In the previous blog post we looked at parsing/generating xml with craur.

Today we'll check, how you can parse csv (even xlsx) files with craur. Craur is a json/xml/csv/xlsx to json/xml/csv/xlsx conversion library.

Usually you might use fgetcsv or some custom code to parse csv, but with craur we have a a simple api for any of those formats, with a consistent api when it comes to throwing exception.

A sample csv-file, looks like this:

Book Name;Book Year;Author Name;Author Age;Book Category
My Book;2012;Hans;32;Fantasy
My second Book;2010;Erwin;10;Comedy

Generating this csv, works with craur like this:

<?php

$craur = new \Craur(array(
    'book' => array(
        array(
            'name' => 'My Book',
            'year' => 2012,
            'author' => 'Paul',
            'age' => '32',
            'genre' => 'Fantasy'
        ),
        array(
            'name' => 'My second Book',
            'year' => '2010',
            'author' => 'Erwin',
            'age' => '10',
            'category' => 'Comedy'
        )
    )
));

$craur->saveToCsvFile('books.csv', array(
    'book[].name',
    'book[].year',
    'book[].author',
    'book[].age',
    'book[].genre'
));

If you want to parse this csv file, you can do this easily with craur in the following way:

<?php

$craur = Craur::createFromCsvFile('books.csv', array(
   'book[].name',
   'book[].year',
   'book[].author',
   'book[].age',
   'book[].genre'
));

var_dump(count($craur->get('book[]')));
# 2

foreach ($craur->get('book[]') as $book)
{
    var_dump($book->get('name'));
}
# My Book
# My second Book

The brackets [] in book[] indicate, that you are expecting an array here. Craur will handle the case, when your csv file is empty and if no element is found, or if there is only one element. In all cases craur will return an array, if the key is suffixed with []. If the key is not suffixed with [], craur will only return the first value.

That's it!

Bonus: With craur it's even possible, to load multi dimension fields in csv/xlsx files. An example may be found in the craur tests and is called csvinputwithmultiplecolumnsandsamemappingtest.php.

In craur, csv, open source, php by @ 10 Dec 2013

comments powered by Disqus

Recent Files

Advertisement

Recent Dev-Articles

Read recently

About

Blogroll