Jump to content

csv


Destramic

Recommended Posts

not difficult.

$users = array  (
                    array ('id' => 1, 'name' => 'Peters, John', 'age' => 22),
                    array ('id' => 2, 'name' => 'Paul',  'age' => 22),
                    array ('id' => 3, 'name' => 'Mary',  'age' => 22)
                );

$fp = fopen('users.csv', 'w');
$first = 1;

foreach ($users as $udata) {
    if ($first) {
        // write header record to csv
        $heads = array_keys($udata);
        fputcsv($fp, $heads);
        $first = 0;
    }
    fputcsv($fp, $udata);
}
fclose($fp);

Going the other way, use fgetcsv() to read each line of data into an array

Link to comment
https://forums.phpfreaks.com/topic/298157-csv/#findComment-1520788
Share on other sites

To get it back into array format you could do something like so:

$path = 'path to file goes here';

$fp = @fopen($path, 'rb');

if($fp === false)
{
    echo 'failed to create/open csv file';
    exit;
}
$start = true;
$headers = array();
$multi = array();

while(($data = fgetcsv($fp,4095)) !== false)
{
    if($start)
    {
       $headers = array_values($data);
       $start = false;
       continue;
    }
    // combine headers with data array to form associative array
    $multi[] = array_combine($headers, $data);
}

print_r($multi);
Link to comment
https://forums.phpfreaks.com/topic/298157-csv/#findComment-1520789
Share on other sites

thank you guys...i was trying to over complicate things ie. trying to csv a array like so and return it

array('1', '2', '2', array('5', '6', '7'))

but all i really needed it for was db rows! :

 

but thank you guys...just what i needed....nice a simple...dunno why i tried over thinking a script for something i don't need 

 

:happy-04: 

Link to comment
https://forums.phpfreaks.com/topic/298157-csv/#findComment-1520853
Share on other sites

If it comes from a db query, why not go straight to the csv?

$sql = "SELECT id, name, age FROM user";
$res = $mysqli->query($sql);

$fp = fopen ('user.csv', 'w');

$row = $res->fetch_assoc();                 // get first row
fputcsv($fp, array_keys($row));             // write headers

do {
    fputcsv($fp, $row);                     // write record
} while ($row = $res->fetch_assoc());
fclose($fp);
Link to comment
https://forums.phpfreaks.com/topic/298157-csv/#findComment-1520854
Share on other sites

thats the plan :)

 

got this for data...so i can cache...the json for one page is like 4000 rows so caching it should save some memory and cpu

<?php

namespace Utility;

use \Exception as Exception;
define('DS', DIRECTORY_SEPARATOR);

class Cache 
{    
    protected $_cache_directory = "C:\\nginx\html\cache\\";
    protected $_lifetime        = 108000;
    protected $_extension       = ".txt";
    protected $_extensions      = array('cache', 'txt', 'csv');    
    public $_filename;
 
    public function save($data, $san = true)
    {
        if (is_null($data))
        {
            return false;
        }        
        
        $filename = $this->get_filename();
        $file     = pathinfo($filename);

        try 
        {
            if (!$this->make_directory($file['dirname']))
            {
                throw new Exception('');
            }
        }
        catch (Exception $exception)
        {
            
        }
        
        $extension = $file['extension'];
        $file      = fopen($filename, "w+");
        
        if ($extension === 'csv')
        { 
             $start = true;
            
            foreach ($data as $csv_data) 
            {
                if ($start) 
                {
                    $keys  = array_keys($csv_data);
                    $start = false;
                    
                    fputcsv($file, $keys);
                }
                
                fputcsv($file, $csv_data);
            }
        }
        else
        {
            fwrite($file, $data);
        }
        
        fclose($file);
        
        $lifetime = time() + $this->get_lifetime();
        touch($filename, $lifetime);
    }
    
    public function load($filename = null)
    {
        if (is_null($filename))
        {
            $filename = $this->get_filename();
        }
        
        if (!file_exists($filename))
        {
            return false;
        }
        
        $file      = pathinfo($filename);
        $extension = $file['extension'];
        
        if ($extension === 'csv')
        {
            $start   = true;
            $headers = array();
            $data    = array();
            
            $file = fopen($filename,'r');
            
            while(($csv_data = fgetcsv($file)) !== false)
            {
                if($start)
                {
                    $headers = array_values($csv_data);
                    $start   = false;
                    
                    continue;
                }
             
                $data[] = array_combine($headers, $csv_data);
            }
            
            fclose($file);
        }
        else
        {
            $data = file_get_contents($filename);
        }

        return $data;
    }
    
    public function remove($filename = null)
    {
        if (is_null($filename))
        {
            return false;
        }
        
        if(!file_exists($filename))
        {
            return false;
        } 
              
        unlink($filename);
        
        return true;
    }
    
    public function is_cached($filename = null)
    {  
        if (is_null($filename))
        {
           return false;
        }
       
        echo $filename = $this->format_filename($filename);
        $this->set_filename($filename);
        
        if (!file_exists($filename))
        {
            return false;
        }

         
        $time = filemtime($filename);
       
        if ($time < time())
        {
            $this->remove($filename);
            return false;
        }
        
        return true;
    }
    
    public function remove_all()
    {
        $files = glob($this->get_cache_directory() . "*");
        
        foreach($files as $file)
        { 
            if(is_file($file))
            {
                unlink($file);
            }
        }
    }
       
    protected function format_filename($filename)
    {
        $filename = $this->get_cache_directory() . $filename;
        
        if (DS === '/')
        {
            $replace = "\\";
        }
        else
        {
            $replace = "/";
        }
             
        if (strpos($filename, $replace))
        {
            $filename = str_replace($replace, DS, $filename);
        }
       
        if (strpos($filename, DS.DS))
        {
            $filename = str_replace(DS.DS, DS, $filename);
        }
        
        $info = pathinfo($filename);

        if (!in_array($info['extension'], $this->_extensions))
        {
            $filename = $info['dirname'] . DS . $info['filename'] . $this->_extension;
        }
        
        return $filename;
    }

    protected function make_directory($directory)
    {
        if (!is_dir($directory))
        {
            mkdir($directory, 0755, true);
            
            return true;
        }
        
        return false;
    }
    
    protected function get_cache_directory()
    {
        return $this->_cache_directory;
    }
        
    protected function set_filename($filename)
    {
        $this->_filename = $filename;
    }
    
    protected function get_filename()
    {
        return $this->_filename;
    }
    
    public function extension($extension)
    {
        if (in_array($extension, $this->_extensions))
        {
            $this->_extension = '.' . $extension;
        }
    }
    
    public function lifetime($lifetime, $period = "days")
    {
        $period = strtolower($period);
        
        switch($period)
        {
            case 'seconds':
                break;
        
            case 'minutes':
                $lifetime = $lifetime * 60;
                break;
        
            case 'hours':
                $lifetime = $lifetime * 60 * 60;
                break;
        
            default:
            case 'days':
                $lifetime = $lifetime * 60 * 60 * 24;
                break;
        
            case 'weeks':
                $lifetime = $lifetime * 60 * 60 * 24 * 7;
                break;
        
            case 'months':
                $lifetime = $lifetime * 60 * 60 * 24 * 30;
                break;
        
            case 'years':
                $lifetime = $lifetime * 60 * 60 * 24 * 365;
                break;
        }
            
        $this->_lifetime = $lifetime;
    }
    
    protected function get_lifetime()
    {
        return $this->_lifetime;
    }
}

$cache = new Cache;


if ($cache->is_cached('json/categories.csv'))
{
    print_r($cache->load());
}
else
{
    // database shizzle
    $data = array(array('name' => 'ricky', 'age' => '28'));
    $cache->save($data);
}   
 ?>
Link to comment
https://forums.phpfreaks.com/topic/298157-csv/#findComment-1520855
Share on other sites

Archived

This topic is now archived and is closed to further replies.



×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.