Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2014
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.59 KB | None | 0 0
  1. public function importproduct() {
  2.     // El archivo csv debe estar en la ruta /app/webroot/csv/nombre.csv
  3.     $filename = WWW_ROOT . DS . 'csv' . DS . 'nombre.csv';
  4.         // open the file
  5.         $handle = fopen($filename, "r");
  6.         // read the 1st row as headings
  7.         $header = fgetcsv($handle);
  8.         // create a message container
  9.         $return = array(
  10.             'messages' => array(),
  11.             'errors' => array(),
  12.         );
  13.         $i = 0;
  14.         $records = 0;
  15.         $data = array();
  16.          // read each data row in the file
  17.         while (($row = fgetcsv($handle)) !== FALSE) {
  18.             // for each header field
  19.             foreach ($header as $k=>$head) {
  20.                 // get the data field from Model.field
  21.                 if (strpos($head,'.')!==false) {
  22.                     $h = explode('.',$head);
  23.                     $data[$h[0]][$h[1]]=(isset($row[$k])) ? $row[$k] : '';
  24.                 }
  25.                 // get the data field from field
  26.                 else {
  27.                     $data[$i]['Product'][$head]=(isset($row[$k])) ? $row[$k] : '';
  28.                     $temp['Product'][$head]=(isset($row[$k])) ? $row[$k] : '';
  29.                     if ($head == 'category') {
  30.                         $temp['Product']['category_id'] = $this->strToUrl($row[$k]);
  31.                     }
  32.                 }
  33.             }
  34.             if ($this->Product->save($temp)) {
  35.                 $records++;
  36.             }
  37.             $i++;
  38.         }
  39.         echo "Fueron grabados ".$records." productos";
  40.         debug($data);
  41.         // close the file
  42.         fclose($handle);
  43.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement