<?php /** * File: SimpleCsv.php * Author: Rumverse * Copyright: 2011 Rumverse * Date: 7/30/2011 * Link: http://ulaptech.blogspot.com * Package: Simple Objects * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details: * http://www.gnu.org/licenses/gpl.html * */ class SimpleCsv { const LINECHARS = 1000; protected $_filename; protected $_resource; protected $_data; protected $_dataMap = array ('field1', 'field2', 'field3', 'field4', 'field5'); public function __construct($filename) { $this->loadFile($filename); } public function loadFile($filename, $accessMode = "r+") { $this->refresh(); if (!empty($filename) && is_file($filename)) { $this->_filename = $filename; $this->_resource = fopen($filename, $accessMode); } return $this; } public function refresh() { $this->_filename = null; $this->_resource = null; $this->_data = null; } public function getArrayData($limit = null) { if (!empty($this->_data) && is_array($this->_data)) { return $this->_data; } else { if (!empty($this->_resource) && is_resource($this->_resource)) { while (($data = fgetcsv($this->_resource, self::LINECHARS, ",")) !== FALSE) { if (!empty($this->_dataMap)) { $this->_data[] = array_combine($this->_dataMap, $data); } else { $this->_data[] = $data; } } fclose($this->_resource); return $this->_data; } } return false; } public function getJsonData($limit = null) { if (empty($this->_data) || !is_array($this->_data)) { $this->getArrayData($limit); } return json_encode($this->_data); } }
Saturday, July 30, 2011
PHP SimpleCsv - Treating CSV Files as Objects
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment