Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
simple mysql to csv export
  • First of this can be improved alot.
    But as I haven't seen any example or questions about it on this forum, I thought sharing this example with you (you = rookies). In the export function add the following (example)
    $products = Model_Products::find()->get();
        $data = "name;price ;category\r\n";
        
        foreach ($products as $product)
        {
         $data .= $product->name . ";";
         $data .= $product->price . ";";
         $data .= $product->category . ";";
         $data .= "\r\n";
        }
          
        if (file_exists(DOCROOT . 'assets/doc/report.csv'))
        {
         File::update(DOCROOT . 'assets/doc', 'report.csv', $data);
        } else {
         File::create(DOCROOT . 'assets/doc', 'report.csv', $data);
         chmod(DOCROOT . 'assets/doc/report.csv', 0777);
        }
    

    As stated before this is an example I use for my project. So, for this i just use a semicolumn (';') to seperate each property of a row.
    to set a newline just use ('\r\n'). I hope someday someone might create an excel converter with the xls extention so multiple worksheets can be used :)
  • *Takes a bow* Thank you, thank you, I'll be here all week.
  • When i do
    Format::factory($products)->to_csv();
    
    i get
    ErrorException [ 4096 ]: Object of class Model_Products could not be converted to string
    
    Do you know why ?
  • Ok, I figured out why it didn't work : I use orm, so I had to write
    $products = Model_Product::query()
     ->get_query()
     ->execute()
     ->as_array();
    
    in place of
    $products = Model_Product::query()
     ->get();
    
  • You should try using
    \Format::factory($products)->to_csv();
    

    The problem with the method you show, is if there are any breaking characters (semi-colons, quotes, commas, etc), the csv is invalid. Good example of another option to do something though!
  • Damn you brains!!!!!! :D Okay, well I totally overlooked this.
    Thanks alot for the info
    So actually I can simply use:
    $data = Format::factory($products)->to_csv();
    File::create(DOCROOT . 'assets/doc', 'prijslijst.csv', $data);
    

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion