Related
I am working on a 2D string with \n new line at the end.
The maze is 1000 x 1000 but I downscales this to 10 x 5 for the sake of readability.
0 means empty space.
S means starting point.
T means target point.
I created a function called cal_path to calculate the path between S and T. However the
result is not correct. I've hard-coded an estimate answer. Any advice/help would be much appreciated.
<?php
$maze='S000000000
0000000000
0000000000
00000000T0
0000000000';
$maze_y=explode(PHP_EOL,$maze);//convert line to array
function show_maze($maze_y){
for ($y=0;$y<count($maze_y);$y++){
for ($x=0;$x<=strlen($maze_y[$y]);$x++){
echo $maze_y[$y][$x];
}
echo "\n";
}
}
function cal_path($maze_y){
// I hardcoded it right now, I am stuck here
return array(
array(1,1),
array(1,2),
array(1,3),
array(2,4),
array(2,5),
array(2,6),
array(3,7),
array(3,8),
);
}
show_maze($maze_y); //original maze
$path=cal_path($maze_y);
foreach ($path as $point){
$maze_y[$point[0]][$point[1]]='P';
}
show_maze($maze_y);
Output:
S000000000
0000000000
0000000000
00000000T0
0000000000
Estimate Output:
S000000000
0PPP000000
0000PPP000
0000000PP0
0000000000
Here's my attempt, but it fails to find a shortest path.
<?php
$maze = '0000000000
0000S00000
0000000000
00000000T0
0000000000';
$maze_y = explode(PHP_EOL, $maze); //convert line to array
function show_maze($maze_y)
{
for ($y = 0; $y < count($maze_y); $y++) {
for ($x = 0; $x < strlen($maze_y[$y]); $x++) {
echo $maze_y[$y][$x];
}
echo "\n";
}
}
function cal_path($maze_y)
{
$found_start = -1;
$found_end = -1;
$row = 0;
foreach ($maze_y as $current) {
for ($x = 0; $x <= strlen($current); $x++) {
if ($found_start == -1) {
$found_start = (strpos($current, 'S') === false) ? '-1' : strpos($current, 'S');
if ($found_start != -1) {
$found_start_y = $row;
}
}
if ($found_end == -1) {
$found_end = (strpos($current, 'T') === false) ? '-1' : strpos($current, 'T');
if ($found_end != -1) {
$found_end_y = $row;
}
}
}
$row++;
}
echo 'start' . $found_start . ' - ' . $found_start_y;
echo "\n";
echo 'end' . $found_end . ' - ' . $found_end_y;
echo "\n";
$step_size_y = $found_end_y - $found_start_y;
$step_size_x = $found_end - $found_start;
echo "step size X $step_size_x Y $step_size_y";
echo "\n";
$start_pointer = array($found_start, $found_start_y);
$maxtry = 100;
$cal_result = array();
while ($maxtry > 0 && ($start_pointer[0] != $found_end || $start_pointer[1] != $found_end_y)) {
$maxtry--;
if ($step_size_x > 1 && $start_pointer[0] != $found_end) {
$start_pointer[0]++;
} else if ($step_size_x < 1 && $start_pointer[0] != $found_end) {
$start_pointer[0]--;
}
if ($step_size_y > 1 && $start_pointer[1] != $found_end_y) {
$start_pointer[1]++;
} else if ($step_size_y < 1 && $start_pointer[1] != $found_end_y) {
$start_pointer[1]--;
}
array_push($cal_result, array($start_pointer[1] , $start_pointer[0] ));
echo 'Path: ' . $start_pointer[0] . ' - ' . $start_pointer[1] . "\n";
}
return $cal_result;
}
show_maze($maze_y); //original maze
$path = cal_path($maze_y);
foreach ($path as $point) {
$maze_y[$point[0]][$point[1]] = 'P';
}
show_maze($maze_y);
You can use the following as a starting point.
It's a simple implementation of the pseudocode at: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Using_a_priority_queue
<?php
require_once 'src/MinQueue.php';
require_once 'src/Dijkstra.php';
require_once 'src/Maze.php';
$maze = Maze::fromString(file_get_contents('maze.txt')); // < a simple text file
$start = $maze->find('S');
$goal = $maze->find('T');
$helper = new Dijkstra(
// return neighbors
function ($a) use ($maze) {
return $maze->getNeighbors($a, ['W']);
},
// calculate the distance
function ($a, $b) use ($maze) {
return $maze->getDistance($a, $b);
}
);
$tStart = microtime(true);
$path = $helper->findPath($start, $goal);
$tEnd = microtime(true);
// export the maze with the path marked with '.'
$mazeStrWithPath = $maze->toString(function ($tile) use ($path) {
return in_array($tile, $path, true) && !in_array($tile->value, ['S', 'T'])
? '.'
: $tile->value
;
});
printf("%s\nin: %.5fs\n\n", $mazeStrWithPath, $tEnd - $tStart);
example output:
_____________________________________________________W_________________
_____________________________________________________W_________________
_____________________________________________________W_________________
_________________W___________________________________W_________________
_________________W___________________________________W_____________T___
_________________W___________________________________W____________.____
_________________W___________________________________W___________._____
_________________W___________________________________W__________.______
_________________W___________________________________W_________._______
_________________W____________________.........______W________.________
_________________W___________________.WWWWWWWWW._____W_______._________
_________________W__________________._W_____...______W______.__________
_________________W_________________.__W____.WWWWWWWWWW_____.___________
_________________W________________.___W_____...............____________
_________________W_____________...____W________________________________
_________________W____________.WWWWWWWW________________________________
_________________W_____________.______W________________________________
_________W_______W______________._____W________________________________
_________W_______W______________._____W________________________________
_________W_______WWWWWWWWWWWWWWW._____W________________________________
_________W_____________________.______W________________________________
_________W____________________._______W________________________________
_________W___________________.________W________________________________
__S...___W__________________._________W________________________________
______.__W_________________.__________W________________________________
_______._W________________.___________W________________________________
________.W_______________.____________W________________________________
_________................_____________W________________________________
Using the following classes:
MinQueue
<?php
declare(strict_types=1);
class MinQueue implements \Countable
{
/**
* #var \SplPriorityQueue
*/
private $queue;
/**
* #var \SplObjectStorage
*/
private $register;
/**
* MinQueue constructor.
*/
public function __construct()
{
$this->queue = new class extends \SplPriorityQueue
{
/** #inheritdoc */
public function compare($p, $q)
{
return $q <=> $p;
}
};
$this->register = new \SplObjectStorage();
}
/**
* #param object $value
* #param mixed $priority
*/
public function insert($value, $priority)
{
$this->queue->insert($value, $priority);
$this->register->attach($value);
}
/**
* #return object
*/
public function extract()
{
$value = $this->queue->extract();
$this->register->detach($value);
return $value;
}
/**
* #inheritdoc
*/
public function contains($value)
{
return $this->register->contains($value);
}
/**
* #inheritdoc
*/
public function count()
{
return count($this->queue);
}
}
Dijkstra
<?php
declare(strict_types=1);
class Dijkstra
{
/**
* #var callable
*/
private $neighbors;
/**
* #var callable
*/
private $length;
/**
* Dijkstra constructor.
*
* #param callable $neighbors
* #param callable $length
*/
public function __construct(callable $neighbors, callable $length)
{
$this->neighbors = $neighbors;
$this->length = $length;
}
/**
* see: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Using_a_priority_queue
*
* #param object $src
* #param object $dst
*
* #return array
*/
public function findPath($src, $dst): array
{
// setup
$queue = new MinQueue();
$distance = new \SplObjectStorage();
$path = new \SplObjectStorage();
// init
$queue->insert($src, 0);
$distance[$src] = 0;
while (count($queue) > 0) {
$u = $queue->extract();
if ($u === $dst) {
return $this->buildPath($dst, $path);
}
foreach (call_user_func($this->neighbors, $u) as $v) {
$alt = $distance[$u] + call_user_func($this->length, $u, $v);
$best = isset($distance[$v]) ? $distance[$v] : INF;
if ($alt < $best) {
$distance[$v] = $alt;
$path[$v] = $u;
if (!$queue->contains($v)) {
$queue->insert($v, $alt);
}
}
}
}
throw new \LogicException('No path found.');
}
/**
* #param object $dst
* #param \SplObjectStorage $path
*
* #return array
*/
private function buildPath($dst, \SplObjectStorage $path): array
{
$result = [$dst];
while (isset($path[$dst]) && null !== $path[$dst]) {
$src = $path[$dst];
$result[] = $src;
$dst = $src;
}
return array_reverse($result);
}
}
Maze
<?php
declare(strict_types=1);
class Maze
{
/**
* #var array
*/
private $tiles = [];
/**
* Maze constructor.
*
* #param array $tiles
*/
private function __construct(array $tiles = [])
{
$this->tiles = $tiles;
}
/**
* #param string $maze
* #param string $rowDelimiter
*
* #return Maze
*/
public static function fromString(string $maze, string $rowDelimiter = "\n"): Maze
{
$tiles = [];
foreach (explode($rowDelimiter, $maze) as $r => $row) {
$rowTiles = [];
foreach (str_split(trim($row)) as $c => $value) {
$rowTiles[] = (object)[
'row' => $r,
'col' => $c,
'value' => $value
];
}
$tiles[] = $rowTiles;
}
return new self($tiles);
}
/**
* #param callable $renderer
* #param string $rowDelimiter
*
* #return string
*/
public function toString(callable $renderer = null, string $rowDelimiter = "\n"): string
{
$renderer = $renderer ?: function ($tile) { return $tile->value; };
$result = [];
foreach ($this->tiles as $r => $row) {
if (!isset($result[$r])) {
$result[$r] = [];
}
foreach ($row as $c => $tile) {
$result[$r][$c] = $renderer($tile);
}
}
return implode($rowDelimiter, array_map('implode', $result));
}
/**
* #param string $value
*
* #return object
*/
public function find(string $value)
{
foreach ($this->tiles as $row) {
foreach ($row as $tile) {
if ($tile->value === $value) {
return $tile;
}
}
}
return null;
}
/**
* #param object $tile
* #param array $filter
*
* #return array
*/
public function getNeighbors($tile, array $filter = []): array
{
$neighbors = [];
foreach ([
[-1, -1], [-1, 0], [-1, 1],
[ 0, -1], [ 0, 1],
[ 1, -1], [ 1, 0], [ 1, 1],
] as $transformation) {
$r = $tile->row + $transformation[0];
$c = $tile->col + $transformation[1];
if (isset($this->tiles[$r][$c]) && !in_array($this->tiles[$r][$c]->value, $filter, true)) {
$neighbors[] = $this->tiles[$r][$c];
}
}
return $neighbors;
}
/**
* #param object $a
* #param object $b
*
* #return float
*/
public function getDistance($a, $b): float
{
$p = $b->row - $a->row;
$q = $b->col - $a->col;
return sqrt($p * $p + $q * $q);
}
}
Download: https://github.com/Yoshix/so-49896590
Just started to work with Propel 2.0 ORM. All tutorials are telling to work with schemas this way:
Create schema in XML/JSON/YAML/PHP file;
Run $ propel model:build
How do I create, or re-create, or update models and data without using the command line but just inside the php scripts? It might be necessary for creating CMS module installers or something like this.
The Answer: Commander Class
A «Reinvent-The-Wheel» approach but I did not found any other way to work with Propel 2 without CLI.
use Propel\Runtime\Propel;
use Propel\Generator\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Application;
/**
* Class Commander
*
* A script-based approach to run Propel commands without the CLI.
*
* Usage:
*
* ```
* $cmd = new Commander('<propel_command>', '<command_arguments>');
* $cmd->run();
* ...
* $cmd->addCommand('<propel_command>', '<command_arguments>');
* $cmd->run();
* ```
*
* In case of migration tasks you must call
* ```
* ...->preMigrate(array('<path_to_schema_files_dir1>', ..., '<path_to_schema_files_dirN>'), '<temp_dir>');
* ```
* to gather all schemas together and analyze 'em with propel:diff.
*
* Then after the diff and migrate are complete you must call ``postMigrate()`` to remove temporary
* schema copies.
*
*/
class Commander
{
private $command,
$parameters,
$migrationTempSource;
public function __construct($cmd = '', $params = '')
{
$this->addCommand($cmd, $params);
}
/**
* Prepare schema files to be analyzed before the migration process.
* #param array $schemaDirs Array of strings with schema directories
* #param string $tmpSchemaDir Temporary directory to copy schemas to.
* This path also must be used as a --schema-dir option value during the
* diff and migrate tasks
* #return boolean $result
*/
public function preMigrate($schemaDirs = array(), $tmpSchemaDir)
{
$result = false;
$filelist = [];
foreach($schemaDirs as $path)
{
if(is_dir($path))
{
$f = $this->seekFiles($path);
$filelist = count($f) > 0 ? array_merge($filelist, $f) : $f;
}
}
if(!file_exists($tmpSchemaDir))
{
mkdir($tmpSchemaDir, 0777, true);
}
foreach($schemaDirs as $path)
{
if(is_dir($path))
{
$f = $this->seekFiles($path);
foreach($f as $file)
{
copy($path . '/' . $file, $tmpSchemaDir . '/' . $file);
}
}
}
$this->migrationTempSource = $tmpSchemaDir;
return $result;
}
/**
* Removes the temporary schema files after the diff and migrate tasks are complete.
*
* #param bool $removeTmpDir Set to true if you want to remove the whole temporary
* directory, not just the schema files.
* #return bool
*/
public function postMigrate($removeTmpDir = false)
{
$result = false;
$dir = scandir($this->migrationTempSource);
foreach($dir as $d)
{
if($d != '.' && $d != '..')
{
unlink($this->migrationTempSource . '/' . $d);
}
}
if($removeTmpDir === true)
{
#rmdir($this->migrationTempSource);
}
return $result;
}
private function seekFiles($dir)
{
$res = [];
if(is_dir($dir))
{
$d = scandir($dir);
foreach($d as $dd)
{
if($dd != '.' && $dd != '..')
{
if((strpos($dd, 'schema.xml') == strlen($dd)-10) || ($dd == 'schema.xml'))
{
$res[] = $dd;
}
}
}
}
return $res;
}
public function addCommand($cmd = '', $params = '')
{
$this->command = $cmd;
$this->parameters = explode(' --', $params);
}
public function run()
{
if($this->command == '') return false;
$callCommandClass = '';
$cmdParts = explode(':', $this->command);
switch($cmdParts[0])
{
case 'config':
switch($cmdParts[1])
{
case 'convert':
$callCommandClass = 'ConfigConvertCommand';
break;
}
break;
case 'diff':
$callCommandClass = 'MigrationDiffCommand';
break;
case 'migration':
switch($cmdParts[1])
{
case 'create':
$callCommandClass = 'MigrationCreateCommand';
break;
case 'diff':
$callCommandClass = 'MigrationDiffCommand';
break;
case 'up':
$callCommandClass = 'MigrationUpCommand';
break;
case 'down':
$callCommandClass = 'MigrationDownCommand';
break;
case 'status':
$callCommandClass = 'MigrationStatusCommand';
break;
case 'migrate':
$callCommandClass = 'MigrationMigrateCommand';
break;
}
break;
case 'model':
switch($cmdParts[1])
{
case 'build':
$callCommandClass = 'ModelBuildCommand';
break;
}
break;
case 'sql':
switch($cmdParts[1])
{
case 'build':
$callCommandClass = 'SqlBuildCommand';
break;
case 'insert':
$callCommandClass = 'SqlInsertCommand';
break;
}
break;
}
$a = [];
foreach($this->parameters as $p)
{
$x = explode('=', $p);
if(count($x) > 1)
{
$a['--'.str_replace('--', '', $x[0])] = trim($x[1]);
}
else
{
$a['--'.str_replace('--', '', $x[0])] = true;
}
}
$commandLine = array('command' => $this->command) + $a;
$app = new Application('Propel', Propel::VERSION);
$cls = '\Propel\Generator\Command'.'\\'.$callCommandClass;
/** #noinspection PhpParamsInspection */
$app->add(new $cls());
$app->setAutoExit(false);
$output = new StreamOutput(fopen("php://temp", 'r+'));
$result = $app->run(new ArrayInput($commandLine), $output);
if(0 !== $result)
{
rewind($output->getStream());
return stream_get_contents($output->getStream());
}
else
{
return true;
}
}
}
And the usage example:
//Convert the configuration file
$cmd = new Commander('config:convert', '--config-dir='.$_SERVER['DOCUMENT_ROOT'].'/propeltest/config --output-dir='.$_SERVER['DOCUMENT_ROOT'].'/propeltest/config');
$cmd->run();
//... or (re)build models
$cmd = new Commander('model:build', '--schema-dir='.$_SERVER['DOCUMENT_ROOT'].'/propeltest/module/schema --output-dir='.$_SERVER['DOCUMENT_ROOT'].'/propeltest/module/models');
$cmd->run();
//... or perform database migration (actually not tested yet :/ )
$cmd = new Commander('migration:diff', '--schema-dir='.$_SERVER['DOCUMENT_ROOT'].'/propeltest/cache/schemacache');
$cmd->preMigrate([$_SERVER['DOCUMENT_ROOT'].'/propeltest/schema', $_SERVER['DOCUMENT_ROOT'].'/propeltest/module/schema'], $_SERVER['DOCUMENT_ROOT'].'/propeltest/cache/schemacache');
$cmd->run(); // runs migrate:diff
$cmd->addCommand('migration:diff', '--schema-dir='.$_SERVER['DOCUMENT_ROOT'].'/propeltest/cache/schemacache'); // prepare to actually migration
$cmd->run(); // perform migration:migrate
$cmd->postMigrate();
I'm getting a PHP fatal error on a cron script used for Commission Junction. It seems in the error_log it keeps updating with
PHP Fatal error: Call to undefined method Mage_Core_Helper_Data::getEscapedCSVData() in /home/lovescen/public_html/app/code/core/Mage/Dataflow/Model/Convert/Parser/Csv.php on line 269
The code on line 269 is
$escapedValue = Mage::helper("core")->getEscapedCSVData(array($value));
And here is the entire code in Csv.php.
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* #category Mage
* #package Mage_Dataflow
* #copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Convert csv parser
*
* #category Mage
* #package Mage_Dataflow
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_Dataflow_Model_Convert_Parser_Csv extends Mage_Dataflow_Model_Convert_Parser_Abstract
{
protected $_fields;
protected $_mapfields = array();
public function parse()
{
// fixed for multibyte characters
setlocale(LC_ALL, Mage::app()->getLocale()->getLocaleCode().'.UTF-8');
$fDel = $this->getVar('delimiter', ',');
$fEnc = $this->getVar('enclose', '"');
if ($fDel == '\t') {
$fDel = "\t";
}
$adapterName = $this->getVar('adapter', null);
$adapterMethod = $this->getVar('method', 'saveRow');
if (!$adapterName || !$adapterMethod) {
$message = Mage::helper('dataflow')->__('Please declare "adapter" and "method" nodes first.');
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
try {
$adapter = Mage::getModel($adapterName);
}
catch (Exception $e) {
$message = Mage::helper('dataflow')->__('Declared adapter %s was not found.', $adapterName);
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
if (!method_exists($adapter, $adapterMethod)) {
$message = Mage::helper('dataflow')->__('Method "%s" not defined in adapter %s.', $adapterMethod, $adapterName);
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
$batchModel = $this->getBatchModel();
$batchIoAdapter = $this->getBatchModel()->getIoAdapter();
if (Mage::app()->getRequest()->getParam('files')) {
$file = Mage::app()->getConfig()->getTempVarDir().'/import/'
. urldecode(Mage::app()->getRequest()->getParam('files'));
$this->_copy($file);
}
$batchIoAdapter->open(false);
$isFieldNames = $this->getVar('fieldnames', '') == 'true' ? true : false;
if (!$isFieldNames && is_array($this->getVar('map'))) {
$fieldNames = $this->getVar('map');
}
else {
$fieldNames = array();
foreach ($batchIoAdapter->read(true, $fDel, $fEnc) as $v) {
$fieldNames[$v] = $v;
}
}
$countRows = 0;
while (($csvData = $batchIoAdapter->read(true, $fDel, $fEnc)) !== false) {
if (count($csvData) == 1 && $csvData[0] === null) {
continue;
}
$itemData = array();
$countRows ++; $i = 0;
foreach ($fieldNames as $field) {
$itemData[$field] = isset($csvData[$i]) ? $csvData[$i] : null;
$i ++;
}
$batchImportModel = $this->getBatchImportModel()
->setId(null)
->setBatchId($this->getBatchModel()->getId())
->setBatchData($itemData)
->setStatus(1)
->save();
}
$this->addException(Mage::helper('dataflow')->__('Found %d rows.', $countRows));
$this->addException(Mage::helper('dataflow')->__('Starting %s :: %s', $adapterName, $adapterMethod));
$batchModel->setParams($this->getVars())
->setAdapter($adapterName)
->save();
//$adapter->$adapterMethod();
return $this;
// // fix for field mapping
// if ($mapfields = $this->getProfile()->getDataflowProfile()) {
// $this->_mapfields = array_values($mapfields['gui_data']['map'][$mapfields['entity_type']]['db']);
// } // end
//
// if (!$this->getVar('fieldnames') && !$this->_mapfields) {
// $this->addException('Please define field mapping', Mage_Dataflow_Model_Convert_Exception::FATAL);
// return;
// }
//
// if ($this->getVar('adapter') && $this->getVar('method')) {
// $adapter = Mage::getModel($this->getVar('adapter'));
// }
//
// $i = 0;
// while (($line = fgetcsv($fh, null, $fDel, $fEnc)) !== FALSE) {
// $row = $this->parseRow($i, $line);
//
// if (!$this->getVar('fieldnames') && $i == 0 && $row) {
// $i = 1;
// }
//
// if ($row) {
// $loadMethod = $this->getVar('method');
// $adapter->$loadMethod(compact('i', 'row'));
// }
// $i++;
// }
//
// return $this;
}
public function parseRow($i, $line)
{
if (sizeof($line) == 1) return false;
if (0==$i) {
if ($this->getVar('fieldnames')) {
$this->_fields = $line;
return;
} else {
foreach ($line as $j=>$f) {
$this->_fields[$j] = $this->_mapfields[$j];
}
}
}
$resultRow = array();
foreach ($this->_fields as $j=>$f) {
$resultRow[$f] = isset($line[$j]) ? $line[$j] : '';
}
return $resultRow;
}
/**
* Read data collection and write to temporary file
*
* #return Mage_Dataflow_Model_Convert_Parser_Csv
*/
public function unparse()
{
$batchExport = $this->getBatchExportModel()
->setBatchId($this->getBatchModel()->getId());
$fieldList = $this->getBatchModel()->getFieldList();
$batchExportIds = $batchExport->getIdCollection();
$io = $this->getBatchModel()->getIoAdapter();
$io->open();
if (!$batchExportIds) {
$io->write("");
$io->close();
return $this;
}
if ($this->getVar('fieldnames')) {
$csvData = $this->getCsvString($fieldList);
$io->write($csvData);
}
foreach ($batchExportIds as $batchExportId) {
$csvData = array();
$batchExport->load($batchExportId);
$row = $batchExport->getBatchData();
foreach ($fieldList as $field) {
$csvData[] = isset($row[$field]) ? $row[$field] : '';
}
$csvData = $this->getCsvString($csvData);
$io->write($csvData);
}
$io->close();
return $this;
}
public function unparseRow($args)
{
$i = $args['i'];
$row = $args['row'];
$fDel = $this->getVar('delimiter', ',');
$fEnc = $this->getVar('enclose', '"');
$fEsc = $this->getVar('escape', '\\');
$lDel = "\r\n";
if ($fDel == '\t') {
$fDel = "\t";
}
$line = array();
foreach ($this->_fields as $f) {
$v = isset($row[$f]) ? str_replace(array('"', '\\'), array($fEnc.'"', $fEsc.'\\'), $row[$f]) : '';
$line[] = $fEnc.$v.$fEnc;
}
return join($fDel, $line);
}
/**
* Retrieve csv string from array
*
* #param array $fields
* #return string
*/
public function getCsvString($fields = array()) {
$delimiter = $this->getVar('delimiter', ',');
$enclosure = $this->getVar('enclose', '');
$escapeChar = $this->getVar('escape', '\\');
if ($delimiter == '\t') {
$delimiter = "\t";
}
$str = '';
foreach ($fields as $value) {
$escapedValue = Mage::helper("core")->getEscapedCSVData(array($value));
$value = $escapedValue[0];
if (strpos($value, $delimiter) !== false ||
empty($enclosure) ||
strpos($value, $enclosure) !== false ||
strpos($value, "\n") !== false ||
strpos($value, "\r") !== false ||
strpos($value, "\t") !== false ||
strpos($value, ' ') !== false) {
$str2 = $enclosure;
$escaped = 0;
$len = strlen($value);
for ($i=0;$i<$len;$i++) {
if ($value[$i] == $escapeChar) {
$escaped = 1;
} else if (!$escaped && $value[$i] == $enclosure) {
$str2 .= $enclosure;
} else {
$escaped = 0;
}
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2.$delimiter;
} else {
$str .= $enclosure.$value.$enclosure.$delimiter;
}
}
return substr($str, 0, -1) . "\n";
}
}
Not sure how to fix this problem. If I could get some help I'd really appreciate it.
Thanks
UPDATE
Here is the code from my app/code/core/Mage/Core/Helper/Data.php file: http://pastie.org/10815259
Does the file app/code/core/Mage/Core/Helper/Data.php have the getEscapedCSVData function in it?
It appears that this function is added by SUPEE-7405. Have you patched your store with this SUPEE?
In my case some previous programer have copy the file
from core
\app\code\core\Mage\Core\Helper\Data.php
to local
app\code\local\Mage\Core\Helper\Data.php
and then apply SUPE PATCH 7405...
it cause that all modifications made by SUPE in data.php where rewrite by the old ones in local folder...
Solution: copy the new data.php to local or made a extension of class (better solution)
I have found a php inventory http://inventory-management.org/ easy but was written in PHP4? and I run now on PHP5. I have found some errors that I have already managed to fix but they are keep coming up so I would like to see if I can managed to run at the end. (As it is really simple script only has 5-7 php files).
Could someone help me please how to fix this error?
Fatal error: Cannot redeclare fputcsv() in C:\xampp\htdocs\Inventory\lib\common.php on line 935
which is:
function fputcsv ($fp, $array, $deliminator=",") {
return fputs($fp, putcsv($array,$delimitator));
}#end fputcsv()
here is the full code:
<?php
/*
*/
/**
* description returns an array with filename base name and the extension
*
* #param filemane format
*
* #return array
*
* #access public
*/
function FileExt($filename) {
//checking if the file have an extension
if (!strstr($filename, "."))
return array("0"=>$filename,"1"=>"");
//peoceed to normal detection
$filename = strrev($filename);
$extpos = strpos($filename , ".");
$file = strrev(substr($filename , $extpos + 1));
$ext = strrev(substr($filename , 0 , $extpos));
return array("0"=>$file,"1"=>$ext);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function UploadFile($source, $destination , $name ="") {
$name = $name ? $name : basename($source);
$name = FileExt($name);
$name[2]= $name[0];
$counter = 0 ;
while (file_exists( $destination . $name[0] . "." . $name[1] )) {
$name[0] = $name[2] . $counter;
$counter ++;
}
copy($source , $destination . $name[0] . "." . $name[1] );
#chmod($destination . $name[0] . "." . $name[1] , 0777);
}
function UploadFileFromWeb($source, $destination , $name) {
$name = FileExt($name);
$name[2]= $name[0];
$counter = 0 ;
while (file_exists( $destination . $name[0] . "." . $name[1] )) {
$name[0] = $name[2] . $counter;
$counter ++;
}
SaveFileContents($destination . $name[0] . "." . $name[1] , $source);
#chmod($destination . $name[0] . "." . $name[1] , 0777);
}
/**
* returns the contents of a file in a string
*
* #param string $file_name name of file to be loaded
*
* #return string
*
* #acces public
*/
function GetFileContents($file_name) {
// if (!file_exists($file_name)) {
// return null;
// }
//echo "<br>:" . $file_name;
$file = fopen($file_name,"r");
//checking if the file was succesfuly opened
if (!$file)
return null;
if (strstr($file_name,"://"))
while (!feof($file))
$result .= fread($file,1024);
else
$result = #fread($file,filesize($file_name));
fclose($file);
return $result;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function SaveFileContents($file_name,$content) {
// echo $file_name;
$file = fopen($file_name,"w");
fwrite($file,$content);
fclose($file);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Debug($what,$pre = 1,$die = 0) {
if (PB_DEBUG_EXT == 1) {
if ($pre == 1)
echo "<pre style=\"background-color:white;\">";
print_r($what);
if ($pre == 1)
echo "</pre>";
if ($die == 1)
die;
}
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function SendMail($to,$from,$subject,$message,$to_name,$from_name) {
if ($to_name)
$to = "$to_name <$to>";
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text; charset=iso-8859-1\n";
if ($from_name) {
$headers .= "From: $from_name <$from>\n";
$headers .= "Reply-To: $from_name <$from>\n";
}
else {
$headers .= "From: $from\n";
$headers .= "Reply-To: $from\n";
}
$headers .= "X-Mailer: PHP/" . phpversion();
return mail($to, $subject, $message,$headers);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function FillVars($var,$fields,$with) {
$fields = explode (",",$fields);
foreach ($fields as $field)
if (!$var[$field])
!$var[$field] = $with;
return $var;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CleanupString($string,$strip_tags = TRUE) {
$string = addslashes(trim($string));
if ($strip_tags)
$string = strip_tags($string);
return $string;
}
define("RX_EMAIL","^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$");
define("RX_CHARS","[a-z\ ]");
define("RX_DIGITS","[0-9]");
define("RX_ALPHA","[^a-z0-9_]");
define("RX_ZIP","[0-9\-]");
define("RX_PHONE","[0-9\-\+\(\)]");
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CheckString($string,$min,$max,$regexp = "",$rx_result = FALSE) {
if (get_magic_quotes_gpc() == 0)
$string = CleanupString($string);
if (strlen($string) < $min)
return 1;
elseif (($max != 0) && (strlen($string) > $max))
return 2;
elseif ($regexp != "")
if ($rx_result == eregi($regexp,$string))
return 3;
return 0;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/// FIRST_NAME:S:3:60,LAST_NAME:S...
function ValidateVars($source,$vars) {
$vars = explode(",",$vars);
foreach ($vars as $var) {
list($name,$type,$min,$max) = explode(":",$var);
switch ($type) {
case "S":
$type = RX_CHARS;
$rx_result = FALSE;
break;
case "I":
$type = RX_DIGITS;
$rx_result = TRUE;
break;
case "E":
$type = RX_EMAIL;
$rx_result = FALSE;
break;
case "P":
$type = RX_PHONE;
$rx_result = TRUE;
break;
case "Z":
$type = RX_ZIP;
$rx_result = FALSE;
break;
case "A":
$type = "";
break;
case "F":
//experimental crap
$type = RX_ALPHA;
$rx_result = TRUE;
//$source[strtolower($name)] = str_replace(" ", "" , $source[strtolower($name)] );
break;
}
//var_dump($result);
if (($result = CheckString($source[strtolower($name)],$min,$max,$type,$rx_result)) != 0)
$errors[] = $name;
}
return is_array($errors) ? $errors : 0;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ResizeImage($source,$destination,$size) {
if (PB_IMAGE_MAGICK == 1)
system( PB_IMAGE_MAGICK_PATH . "convert $source -resize {$size}x{$size} $destination");
else
copy($source,$destination);
}
/**
* uses microtime() to return the current unix time w/ microseconds
*
* #return float the current unix time in the form of seconds.microseconds
*
* #access public
*/
function GetMicroTime() {
list($usec,$sec) = explode(" ",microtime());
return (float) $usec + (float) $sec;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetArrayPart($input,$from,$count) {
$return = array();
$max = count($input);
for ($i = $from; $i < $from + $count; $i++ )
if ($i<$max)
$return[] = $input[$i];
return $return;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ReplaceAllImagesPath($htmldata,$image_path) {
$htmldata = stripslashes($htmldata);
// replacing IE formating style
$htmldata = str_replace("<IMG","<img",$htmldata);
// esmth, i dont know why i'm doing
preg_match_all("'<img.*?>'si",$htmldata,$images);
//<?//ing edit plus
foreach ($images[0] as $image)
$htmldata = str_replace($image,ReplaceImagePath($image,$image_path),$htmldata);
return $htmldata;//implode("\n",$html_out);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ReplaceImagePath($image,$replace) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
//getting only image name
$image_arr[$i][1] = strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/")));
// building the image back
$image_arr[$i][1] = "\"" . $replace . $image_arr[$i][1] . "\"";
$image_arr[$i] = implode ("=",$image_arr[$i]);
}
}
// adding tags
return "<" . implode(" ",$image_arr) . ">";
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function DowloadAllImages($images,$path) {
foreach ($images as $image)
#SaveFileContents($path ."/".ExtractFileNameFromPath($image),#implode("",#file($image)));
}
function GetAllImagesPath($htmldata) {
$htmldata = stripslashes($htmldata);
// replacing IE formating style
$htmldata = str_replace("<IMG","<img",$htmldata);
// esmth, i dont know why i'm doing
preg_match_all("'<img.*?>'si",$htmldata,$images);
//<?//ing edit plus
foreach ($images[0] as $image)
$images_path[] = GetImageName($image);
return $images_path;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetImagePath($image) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
return strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/")));;
}
}
// adding tags
return "";
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetImageName($image) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
return $image_arr[$i][1];
}
}
// adding tags
return "";
}
/**
* reinventing the wheel [badly]
*
* #param somthin
*
* #return erroneous
*
* #access denied
*/
function ExtractFileNameFromPath($file) {
//return strrev(substr(strrev($file),0,strpos(strrev($file),"/")));
// sau ai putea face asha. umpic mai smart ca mai sus dar tot stupid
// daca le dai path fara slashes i.e. un filename prima returneaza "" asta taie primu char
//return substr($file,strrpos($file,"/") + 1,strlen($file) - strrpos($file,"/"));
// corect ar fi cred asha [observa smart usage`u de strRpos]
//return substr($file,strrpos($file,"/") + (strstr($file,"/") ? 1 : 0),strlen($file) - strrpos($file,"/"));
// sau putem folosi tactica `nute mai caca pe tine and rtm' shi facem asha
return basename($file);
// har har :]]
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function RemoveArraySlashes($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = RemoveArraySlashes($item);
else
$array[$key] = stripslashes($item);
return $array;
}
function AddArraySlashes($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = AddArraySlashes($item);
else
$array[$key] = addslashes($item);
return $array;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Ahtmlentities($array) {
if (is_array($array))
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ahtmlentities($item);
else
$array[$key] = htmlentities(stripslashes($item),ENT_COMPAT);
else
return htmlentities(stripslashes($array),ENT_COMPAT);
return $array;
}
function AStripSlasshes($array) {
if (is_array($array))
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = AStripSlasshes($item);
else
$array[$key] = stripslashes($item);
else
return stripslashes($array);
return $array;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Ahtml_entity_decode($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ahtml_entity_decode($item);
else
$array[$key] = html_entity_decode($item,ENT_COMPAT);
return $array;
}
function array2xml ($name, $value, $indent = 1)
{
$indentstring = "\t";
for ($i = 0; $i < $indent; $i++)
{
$indentstring .= $indentstring;
}
if (!is_array($value))
{
$xml = $indentstring.'<'.$name.'>'.$value.'</'.$name.'>'."\n";
}
else
{
if($indent === 1)
{
$isindex = False;
}
else
{
$isindex = True;
while (list ($idxkey, $idxval) = each ($value))
{
if ($idxkey !== (int)$idxkey)
{
$isindex = False;
}
}
}
reset($value);
while (list ($key, $val) = each ($value))
{
if($indent === 1)
{
$keyname = $name;
$nextkey = $key;
}
elseif($isindex)
{
$keyname = $name;
$nextkey = $name;
}
else
{
$keyname = $key;
$nextkey = $key;
}
if (is_array($val))
{
$xml .= $indentstring.'<'.$keyname.'>'."\n";
$xml .= array2xml ($nextkey, $val, $indent+1);
$xml .= $indentstring.'</'.$keyname.'>'."\n";
}
else
{
$xml .= array2xml ($nextkey, $val, $indent);
}
}
}
return $xml;
}
function GetPhpContent($file) {
if (file_exists($file) ) {
$data = GetFileContents($file);
//replacing special chars in content
$data = str_replace("<?php","",$data);
$data = str_replace("?>","",$data);
return $data;
}
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function KeyArray($array,$recurse = 0 , $count = 1) {
if (is_array($array)) {
foreach ($array as $key => $val) {
$array[$key]["key"] = $count ++;
if ($recurse) {
foreach ($array[$key] as $k => $val)
if (is_array($val)) {
KeyArray($array[$key][$k] , $recurse , $count);
}
}
}
}
return $count + 1;
}
function RandomWord( $passwordLength ) {
$password = "";
for ($index = 1; $index <= $passwordLength; $index++) {
// Pick random number between 1 and 62
$randomNumber = rand(1, 62);
// Select random character based on mapping.
if ($randomNumber < 11)
$password .= Chr($randomNumber + 48 - 1); // [ 1,10] => [0,9]
else if ($randomNumber < 37)
$password .= Chr($randomNumber + 65 - 10); // [11,36] => [A,Z]
else
$password .= Chr($randomNumber + 97 - 36); // [37,62] => [a,z]
}
return $password;
}
function DeleteFolder($file) {
if (file_exists($file)) {
chmod($file,0777);
if (is_dir($file)) {
$handle = opendir($file);
while($filename = readdir($handle)) {
if ($filename != "." && $filename != "..") {
DeleteFolder($file."/".$filename);
}
}
closedir($handle);
rmdir($file);
} else {
unlink($file);
}
}
}
function GenerateRecordID($array) {
$max = 0;
if (is_array($array)) {
foreach ($array as $key => $val)
$max = ($key > $max ? $key : $max);
return $max + 1;
}
else return 1;
}
/*****************************************************
Links cripting for admin
DO NOT TOUCH UNLKESS YOU KNOW WHAT YOU ARE DOING
*****************************************************/
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CryptLink($link) {
if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1)) {
if (stristr($link,"javascript:")) {
/* if (stristr($link,"window.location=")) {
$pos = strpos($link , "window.location=");
$js = substr($link , 0 , $pos + 17 );
$final = substr($link , $pos + 17 );
$final = substr($final, 0, strlen($final) - 1 );
//well done ... crypt the link now
$url = #explode("?" , $final);
if (!is_array($url))
$url[0] = $final;
$tmp = str_replace( $url[0] . "?" , "" , $final);
$uri = urlencode(urlencode(base64_encode(str_rot13($tmp))));
$link = $js . $url[0] . "?" . $uri . md5($uri) . "'";
}
*/
} else {
$url = #explode("?" , $link);
if (!is_array($url))
$url[0] = $link;
$tmp = str_replace( $url[0] . "?" , "" , $link);
$uri = urlencode(urlencode(base64_encode(str_rot13($tmp))));
$link = $url[0] . "?" . $uri . md5($uri);
}
}
return $link;
}
/************************************************************************/
/* SOME PREINITIALISATION CRAP*/
if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1) ) {
$key = key($_GET);
if (is_array($_GET) && (count($_GET) == 1) && ($_GET[$key] == "")) {
$tmp = $_SERVER["QUERY_STRING"];
//do the md5 check
$md5 = substr($tmp , -32);
$tmp = substr($tmp , 0 , strlen($tmp) - 32);
if ($md5 != md5($tmp)) {
//header("index.php?action=badrequest");
//exit;
die("Please dont change the links!");
}
$tmp = str_rot13(base64_decode(urldecode(urldecode($tmp))));
$tmp_array = #explode("&" , $tmp);
$tmp_array = is_array($tmp_array) ? $tmp_array : array($tmp);
if (is_array($tmp_array)) {
foreach ($tmp_array as $key => $val) {
$tmp2 = explode("=" , $val);
$out[$tmp2[0]] = $tmp2[1];
}
} else {
$tmp2 = explode("=" , $tmp);
$out[$tmp2[0]] = $tmp2[1];
}
$_GET = $out;
}
}
/***********************************************************************/
function ArrayReplace($what , $with , $array ) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ArrayReplace($what , $with , $item);
else
$array[$key] = str_replace($what , $with , $item);
return $array;
}
function stri_replace( $find, $replace, $string )
{
$parts = explode( strtolower($find), strtolower($string) );
$pos = 0;
foreach( $parts as $key=>$part ){
$parts[ $key ] = substr($string, $pos, strlen($part));
$pos += strlen($part) + strlen($find);
}
return( join( $replace, $parts ) );
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GMTDate($format , $date) {
global $_GMT;
return date($format , $date - $_GMT);
}
function putcsv ($array, $deliminator=",") {
$line = "";
foreach($array as $val) {
# remove any windows new lines,
# as they interfere with the parsing at the other end
$val = str_replace("\r\n", "\n", $val);
# if a deliminator char, a double quote char or a newline
# are in the field, add quotes
if(ereg("[$deliminator\"\n\r]", $val)) {
$val = '"'.str_replace('"', '""', $val).'"';
}#end if
$line .= $val.$deliminator;
}#end foreach
# strip the last deliminator
$line = substr($line, 0, (strlen($deliminator) * -1));
# add the newline
$line .= "\n";
# we don't care if the file pointer is invalid,
# let fputs take care of it
return $line;
}#end fputcsv()
function fputcsv ($fp, $array, $deliminator=",") {
return fputs($fp, putcsv($array,$delimitator));
}#end fputcsv()
/**
* description
*
* #param
*
* #return
*
* #access
*/
function is_subaction($sub,$action) {
return (bool)($_GET["sub"] == $sub) && ($_GET["action"] == $action);
}
?>
many thanks in advance
fputcsv() is a built in PHP function. This means you cannot name your own function the same thing.
If you need this code to work with PHP4, just check to see if the function exists first, then if not, create your own.
if (!function_exists('fputcsv')) {
// Your definition here
}
This might be quite simple but I am stumped . Here is what I am trying to do load a csv file into a an entity . I found a php plugin but couldn't figure out how to install so I downloaded the plugin and took the script to read a csv file into my bundle Acme\StoreBundle and actually placed the script (sfCsvReader.php) in the entity folder in the bundle when I attempt to run this on the web I get the following error
Fatal error: Class 'Acme\StoreBundle\Controller\sfCsvReader' not found in /home/jan/symfonysandbox/src/Acme/StoreBundle/Controller/LoadCSVController.php on line 26
My Controller file is as follows
<?php
namespace Acme\StoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Acme\StoreBundle\Entity\Congress;
use Acme\StoreBundle\Entity\sfCsvReader;
use Symfony\Component\HttpFoundation\Response;
class LoadCSVController extends Controller
{
/**
* #Route("/load/{name}")
* #Template()
*/
public function indexAction()
{
$congress = new Congress();
$path = '~/Documents/congress.csv';
$reader = new sfCsvReader($path);
$reader->setSelectColumns('column_A, column_B');
$reader->open();
while ($data = $reader->read())
{
$congress->setTitle($data['column_A']);
$congress->setName($data['column_B']);
$em = $this->getDoctrine()->getManager();
$em->persist($congress);
$em->flush();
return new Response('Created congress id '.$congress->getId() .'for'.$congress->getTitle().'for'.$congress->getName());
}
$reader->close();
}
}
the script its calling is
sfCsvReader
<?php
namespace Acme\StoreBundle\Controller;
/**
* sfCsvReader
* by Carlos Escribano <carlos#markhaus.com>
*
* $csv = new sfCsvReader("/path/to/a/csv/file.csv");
* $csv->open();
* $csv->setSelectColumns('field_A, field_B'); // or array('field_A', 'field_B')
* while ($data = $csv->read())
* {
* // do something with $data['field_A'] and $data['field_B']
* }
* $csv->close();
*
* --- Alternative ---
* $csv = new sfCsvReader("/path/to/a/csv/file.csv");
* $csv->setSelectColumns('field_A, field_B'); // or array('field_A', 'field_B')
* $csv->open();
* ...
* --- Alternative: NUMERICAL INDEXES ---
* $csv = new sfCsvReader("/path/to/a/csv/file.csv");
* $csv->open();
* while ($data = $csv->read())
* {
* // do something with $data[0] and $data[1]
* }
* $csv->close();
*
*
* --- CHARSET ---
* $to = 'ISO-8859-1';
* $from = 'UTF-8';
* $csv->setCharset($to);
* $csv->setCharset($to, $from);
*/
class sfCsvReader
{
private
$header;
private
$file,
$path,
$initialized;
private
$length,
$delimiter,
$enclosure,
$to,
$from;
/**
* #param string $path Path to the file to read
* #param char $delimiter Character delimiting fields (Optional)
* #param char $enclosure Character enclosing fields (Optional)
* #param integer $length PHP's fgetcsv length parameter (Optional)
*/
function __construct($path, $delimiter = ',', $enclosure = '"', $length = null)
{
$this->path = $path;
$this->length = $length;
$this->delimiter = $delimiter;
$this->enclosure = $enclosure;
$this->header = array(
'map' => null,
'selected' => array()
);
$this->initialized = false;
}
public function close()
{
if ($this->file !== null)
{
fclose($this->file);
$this->file = null;
$this->initialized = false;
}
}
public function open($path = null)
{
$this->close();
if ($path !== null)
{
$this->path = $path;
}
if (!($this->file = fopen($this->path, "r")))
{
throw new Exception("File can not be opened (".$this->path.").");
}
$this->initialized = true;
$this->map();
}
public function setSelectColumns($selected = array())
{
$this->test = true;
if (!is_array($selected))
{
$selected = explode(',', preg_replace('/\s+/', '', $selected));
}
$this->header['selected'] = $selected;
$this->map();
}
public function clearSelectColumns()
{
$this->header['selected'] = array();
$this->map();
}
private function map()
{
if ($this->initialized)
{
$this->all = false;
$x = count($this->header['selected']); // N. of selected columns
$y = 0; // N. of real columns
$z = 0; // N. of matching columns
if ($x == 0)
{ // No selection. All fields.
$this->header['map'] = null;
}
else
{
$this->header['map'] = array();
fseek($this->file, 0, SEEK_SET);
if ($line = fgetcsv($this->file, $this->length, $this->delimiter, $this->enclosure))
{
$y = count($line);
if ($y > 0)
{
$common = array_intersect($line, $this->header['selected']);
$z = count($common);
if (($y < $x) || (($x > $z) && ($z > 0)))
{ // More columns in selection than in file or less common columns than selection
throw new Exception("Too much columns or non existing columns in selection (LINE: $y, SEL: $x, COMMON: $z).");
}
if ($z == 0)
{ // Relaxed Mapping: 0 matches found, numerical.
foreach ($this->header['selected'] as $i => $name)
{
$this->header['map'][$name] = $i;
}
fseek($this->file, 0, SEEK_SET);
}
else if ($z == $x)
{ // Absolute Mapping: First line is header.
foreach ($line as $i => $name)
{
$this->header['map'][$name] = $i;
}
}
} // Has columns
} // Read line
} // N columns selected
} // Initialized
}
public function read()
{
if (!$this->initialized)
{
throw new Exception('sfCsvReader is not ready.');
}
if ($line = fgetcsv($this->file, $this->length, $this->delimiter, $this->enclosure))
{
if (is_array($this->header['map']))
{
$res = array();
foreach ($this->header['selected'] as $name)
{
if ($this->to !== null)
{
$res[$name] = $this->encode($line[$this->header['map'][$name]], $this->to, $this->from);
}
else
{
$res[$name] = $line[$this->header['map'][$name]];
}
}
return $res;
}
else
{
return $line;
}
}
else
{
return null;
}
}
private function encode($str, $to, $from = null)
{
if ($from === null)
{
$from = mb_detect_encoding($str);
}
if (function_exists('iconv'))
{
return iconv($from, $to, $str);
}
else
{
return mb_convert_encoding($str, $to, $from);
}
}
public function setCharset($to, $from = null)
{
$this->to = $to;
$this->from = $from;
}
function __destruct()
{
$this->close();
}
}
Are you loading the script before call them?
Try to add the following code to app/autoload.php inside the $loader->registerNamespaces(array(... array declaration:
'SfCsvReader' => __DIR__.'/../src/Acme/StoreBundle/Entity/sfCsvReader.php',
After that, rename the namespace inside the sfCsvReader.php file to namespace SfCsvReader\sfCsvReader; and replace the namespace requesting in your controller to use SfCsvReader\sfCsvReader;.
This should work fine, but maybe you should move your file to a more proper directory, for example in the vendor/sfCsvReader directory of the project.
You can follow the recommendations in the Symfony 2.0 documentation.
The autoloading info are in the following link The ClassLoader Component.
More info about namespaces can be found in php.net.