2015-12-02 3 views
3

Я создал класс для использования с созданием файлов;Использование PHP для создания файлов и каталогов

Это класс, который у меня есть:

<?php 
class XLSX 
{ 
    /** @var resource */ 
    private $handle; 
    /** @var array */ 
    private $data; 
    /** @var array */ 
    private $headings; 
    /** @var bool */ 
    private $finished = true; 
    /** @var string */ 
    private $filename; 

    /** 
    * Creates the class, must be done each time a file is written to as the handle is stored. 
    * @param string $filename The file to be written to, will create the file if it does not exist 
    */ 
    public function __construct($filename) 
    { 
     $this->MakeDir(dirname($filename)); 
     $this->MakeFile($filename); 
     $this->finished = false; 
    } 

    /** 
    * Set the headers for the XSLX 
    * @param array $headers 
    * @return bool 
    */ 
    public function SetHeaders($headers) 
    { 
     return $this->AddToArray("headings", $headers); 
    } 

    /** 
    * Get the headers that were set, if not set return null. 
    * @return array|null 
    */ 
    public function GetHeaders() 
    { 
     return !empty($this->headings) ? $this->headings : null; 
    } 

    /** 
    * Set the data for the XSLX 
    * @param array $headers 
    * @return bool 
    */ 
    public function SetData($data) 
    { 
     return $this->AddToArray("data", $data); 
    } 

    /** 
    * Get the data that was set, if not set return null. 
    * @return array|null 
    */ 
    public function GetData() 
    { 
     return !empty($this->data) ? $this->data : null; 
    } 

    /** 
    * Get the filename 
    * @return string 
    */ 
    public function GetFilename() 
    { 
     return $this->filename; 
    } 

    /** 
    * Write the data that is needed for the file to the file 
    * @return bool 
    */ 
    public function Write() 
    { 
     if (!$this->finished && isset($this->handle)) 
     { 
      if ($this->GetHeaders() == null || $this->GetData() == null) 
      { 
       return false; 
      } 
      foreach ($this->GetHeaders() as $header) 
      { 
       fwrite($this->handle, $header . "\t"); 
      } 
      fwrite($this->handle, "\n"); 
      foreach ($this->GetData() as $data) 
      { 
       if (is_array($data)) 
       { 
        foreach ($data as $d) 
        { 
         fwrite($this->handle, $d . "\t"); 
        } 
        fwrite($this->handle, "\n"); 
       } 
       else 
       { 
        fwrite($this->handle, $data . "\t"); 
       } 
      } 
     } 
     return false; 
    } 

    /** 
    * Set the handle and all data back to default, ready to recall a new instance. 
    * @return void 
    */ 
    public function Finish() 
    { 
     fclose($this->handle); 
     $this->handle = null; 
     $this->data = null; 
     $this->headings = null; 
     $this->finished = true; 
     $this->filename = null; 
    } 

    /** 
    * Count the amount of working days in a month 
    * @param integer $year 
    * @param integer $month 
    * @return double|integer 
    */ 
    public function CountDays($year, $month) 
    { 
     $count = 0; 
     $counter = mktime(0, 0, 0, $month, 1, $year); 
     while (date("n", $counter) == $month) 
     { 
      if (in_array(date("w", $counter), array(0, 6)) == false) 
      { 
       $count++; 
      } 
      $counter = strtotime("+1 day", $counter); 
     } 
     return $count; 
    } 

    /** 
    * Makes a directory 
    * @param string $dirname 
    */ 
    private function MakeDir($dirname) 
    { 
     if (!is_dir($dirname)) 
     { 
      @mkdir($dirname, 777, true) ?: die("Failed to create the required directory."); 
     } 
    } 

    /** 
    * Creates a file to be used 
    * @param string $filename 
    */ 
    private function MakeFile($filename) 
    { 
     if (file_exists($filename)) 
     { 
      for ($i = 1; $i <= 200; $i++) 
      { 
       $fname = basename($filename); 
       $base = str_replace($fname, "", $filename); 
       $explded_base_name = explode(".", $fname); 
       if (!file_exists("{$base}{$explded_base_name[0]}_{$i}.{$explded_base_name[1]}")) 
       { 
        $this->handle = fopen("{$base}{$explded_base_name[0]}_{$i}.{$explded_base_name[1]}", "w"); 
        $this->filename = $base . str_replace(" ", "%20", "{$explded_base_name[0]}_{$i}.{$explded_base_name[1]}"); 
        break; 
       } 
      } 
     } 
     else 
     { 
      $this->handle = fopen($filename, "w"); 
      $this->filename = $filename; 
     } 
    } 

    /** 
    * Add items to an array 
    * @param string $arrayName 
    * @param mixed $values 
    * @return bool 
    */ 
    private function AddToArray($arrayName, $values) 
    { 
     if (!$this->finished) 
     { 
      foreach($values as $val) 
      { 
       $this->{$arrayName}[] = $val; 
      } 
     } 
     return !empty($this->{$arrayName}) ? true : false; 
    } 
} 
?> 

Теперь это работает прекрасно, кроме одного мертвой точки; способ создания имени файла на моем сервере.

Для этого у меня есть /var/www/vhosts/mysite.co.uk/_exports/payslips/ как каталог, к которому я пытаюсь писать. Как вы можете видеть в своем коде, у меня есть эта строка:

$fname = explode(".", $filename); 

Но, что вызывает проблемы при восстановления имени файла, например, мое имя файла выходит как:

/var/www/vhosts/mysite.co 
// Should be: 
/var/www/vhosts/mysite.co.uk/_exports/payslips/02 Dec 2015/{username}.xls 

Каков наилучший способ перестроить имя файла для этого метода __construct?

Я использую это как например:

$fname = "/var/www/vhosts/mysite.co.uk/_exports/payslips/" . date("j M Y") . "/" . $_SESSION['loginUsername'] . ".xls"; 
$xlsx = new XLSX($fname); 
+0

[базовое имя] (http://php.net/manual/en/function .basename.php) даст имя файла, а затем вы сможете взорвать только его. – mrun

+0

Это фантастика! Я отдам! –

+0

также вы можете попытаться не использовать имена каталогов с пробелами, используйте 'date (" j-M-Y ")', чтобы вы могли в дальнейшем разбирать его безопасно –

ответ

2

Вы можете проверить функцию basename, которая будет возвращать только имя файла, и вы можете работать только с ним.

0

С помощью @mrun, это решение, которое было сделано (отправил, чтобы помочь только людям):

/** 
* Creates the class, must be done each time a file is written to as the handle is stored. 
* @param string $filename The file to be written to, will create the file if it does not exist 
*/ 
public function __construct($filename) 
{ 
    $dirname = dirname($filename); 
    if (!is_dir($dirname)) 
    { 
     @mkdir($dirname, 777, true) ?: die("Failed to create the required directory."); 
    } 
    if (file_exists($filename)) 
    { 
     for ($i = 1; $i <= 200; $i++) 
     { 
      $fname = basename($filename); 
      $base = str_replace($fname, "", $filename); 
      $explded_base_name = explode(".", $fname); 
      if (!file_exists("{$base}{$explded_base_name[0]}_{$i}.{$explded_base_name[1]}")) 
      { 
       $this->handle = fopen("{$base}{$explded_base_name[0]}_{$i}.{$explded_base_name[1]}", "w"); 
       $this->filename = $base . str_replace(" ", "%20", "{$explded_base_name[0]}_{$i}.{$explded_base_name[1]}"); 
       break; 
      } 
     } 
    } 
    else 
    { 
     $this->handle = fopen($filename, "w"); 
     $this->filename = $filename; 
    } 
    $this->finished = false; 
}  mkdir($dirname, 0777, true) ?: die("Failed to create the required directory."); 
    } 
    if (file_exists($filename)) 
    { 
     for ($i = 1; $i <= 200; $i++) 
     { 
      $fname = basename($filename); 
      $base = str_replace($fname, "", $filename); 
      $explded_base_name = explode(".", $fname); 
      if (!file_exists("{$base}{$explded_base_name[0]}_{$i}.{$explded_base_name[1]}")) 
      { 
       $this->handle = fopen("{$explded_base_name[0]}_{$i}.{$explded_base_name[1]}", "w"); 
       $this->filename = $base . str_replace(" ", "%20", "{$explded_base_name[0]}_{$i}.{$explded_base_name[1]}"); 
       break; 
      } 
     } 
    } 
    else 
    { 
     $this->handle = fopen($filename, "w"); 
     $this->filename = $filename; 
    } 
    $this->finished = false; 
    print $this->filename; 
} 
Смежные вопросы