James Revillini

Say 'no' to styrofoam.

Category: php

php

Parse an uploaded CSV file in 2 lines in PHP/CakePHP

Nasty but gets it done:

or, if you want to be even more crazy, in 1 (note, config options are inline but I left the assignments so they are findable):

or, if you want it to be one expression, but more readable:

In the examples above, I’m assuming you already know the temporary name of the uploaded file. In regular PHP, you could prepend this code with

In CakePHP, you might just replace $tmpname with $this->data[‘Whatever’][‘csv’][‘tmp_name’];
This kind of assumes you had done something like this on the form page:

CakePHP 1.1.x, Vendors, and domPDF

Wow – for a built in feature, this sure was a pain in the ass to get working.  I’m talking about using the ‘vendors’ functionality in CakePHP 1.1.x (I’m at .19), of course, and in this case, my external class was domPDF.

First of all, they never really cover how to use the vendor function in the CakePHP Docs.  Usually when that happens, it’s one of those things that’s so painfully simple, you could get drunk, trip on something and accidentally get it working.

But no – here’s what you need to do in plain english.  (HOWTO writers – please take note that I include like every step and try not to assume too much knowledge on the part of the struggling user.  It would be great if you started writing HOWTOs like this as well.)

 

  1. download dompdf
  2. extract it to a temp area.  you should have a folder like dompdf-0.5.1 containing subfolders like ‘include’, ‘lib’, and ‘www’.
  3. rename the dompdf-0.5.1 folder to ‘dompdf
  4. move the dompdf folder to your {CAKE_INSTALL}/app/vendors/ directory.
  5. copy and paste my sample code (below) into your controller, before the closing }
  6. upload everything to your webserver, and now try it using a url like http://yoursite.com/cake/posts/pdf
  7. if you get an error, or a blank screen, check your apache server log.  if you see something like PDFlib exception (fatal): [1202] PDF_set_parameter: Unknown key ‘objorient’ then you need to do one more thing.  
    1. open {CAKE_INSTALL}/app/vendors/dompdf/dompdf_config.inc.php
    2. find define(“DOMPDF_PDF_BACKEND”, “auto”);
    3. change it to define(“DOMPDF_PDF_BACKEND”, “CPDF”);
    4. if you want to know why you just did that, it’s because the PECL PDF library is crashing, or you don’t have it installed or something.
    5. go back to step 6.
  8. now customize everything to how you need it.

© 2017 James Revillini

Theme by Anders NorenUp ↑