본문 바로가기

프로그래밍

[php] composer 없이 spreadsheet 사용하기

반응형

phpspreadsheet를 cafe24에서 사용하려고 하니 composer가 필요했다.
composer는 패키지들의 의존성 도구로 별도 잘못 설치하다가 꼬일 수 있는 부분을 해결해주는 도구이다. 
하지만 대부분의 일반 호스팅에서는 지원을 하지 않고 있으니 사용할 수가 없다 ㅠㅠ;;; 
해서... 찾아보니 역시 방법이 있었다... 
차후에도 사용하려고 여기에 기재해 놓는다. 

1. phpspreadsheet 다운받기 
  - https://github.com/PHPOffice/PhpSpreadsheet 

 

PHPOffice/PhpSpreadsheet

A pure PHP library for reading and writing spreadsheet files - PHPOffice/PhpSpreadsheet

github.com

2. 다운받은 폴더의 src폴더를 PhpOffice로 변경한 후 웹상에 폴더에 업로드 한다. 

3. composer에는 PSR Cache Interface라는게 존재하는데 이걸 대응할 폴더와 파일을 만든다.
    - PhpOffice에 Psr폴더를 만든다. 

    - Psr폴더에 autoloader.php와 Psr.php를 만든다. 
    - autoloader.php

<?php
spl_autoload_register(function ($class_name) {
	$preg_match = preg_match('/^Psr\\\/', $class_name);

	if (1 === $preg_match) {
		require_once(__DIR__ . '/Psr.php');
	} else if (false === $preg_match) {
		assert(false, 'Error de preg_match().');
	}
});

    - Psr.php 

<?php

namespace Psr\SimpleCache;

interface CacheInterface
{
    /**
     * Fetches a value from the cache.
     *
     * @param string $key     The unique key of this item in the cache.
     * @param mixed  $default Default value to return if the key does not exist.
     *
     * @return mixed The value of the item from the cache, or $default in case of cache miss.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function get($key, $default = null);

    /**
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
     *
     * @param string                 $key   The key of the item to store.
     * @param mixed                  $value The value of the item to store. Must be serializable.
     * @param null|int|\DateInterval $ttl   Optional. The TTL value of this item. If no value is sent and
     *                                      the driver supports TTL then the library may set a default value
     *                                      for it or let the driver take care of that.
     *
     * @return bool True on success and false on failure.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function set($key, $value, $ttl = null);

    /**
     * Delete an item from the cache by its unique key.
     *
     * @param string $key The unique cache key of the item to delete.
     *
     * @return bool True if the item was successfully removed. False if there was an error.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function delete($key);

    /**
     * Wipes clean the entire cache's keys.
     *
     * @return bool True on success and false on failure.
     */
    public function clear();

    /**
     * Obtains multiple cache items by their unique keys.
     *
     * @param iterable $keys    A list of keys that can obtained in a single operation.
     * @param mixed    $default Default value to return for keys that do not exist.
     *
     * @return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if $keys is neither an array nor a Traversable,
     *   or if any of the $keys are not a legal value.
     */
    public function getMultiple($keys, $default = null);

    /**
     * Persists a set of key => value pairs in the cache, with an optional TTL.
     *
     * @param iterable               $values A list of key => value pairs for a multiple-set operation.
     * @param null|int|\DateInterval $ttl    Optional. The TTL value of this item. If no value is sent and
     *                                       the driver supports TTL then the library may set a default value
     *                                       for it or let the driver take care of that.
     *
     * @return bool True on success and false on failure.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if $values is neither an array nor a Traversable,
     *   or if any of the $values are not a legal value.
     */
    public function setMultiple($values, $ttl = null);

    /**
     * Deletes multiple cache items in a single operation.
     *
     * @param iterable $keys A list of string-based keys to be deleted.
     *
     * @return bool True if the items were successfully removed. False if there was an error.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if $keys is neither an array nor a Traversable,
     *   or if any of the $keys are not a legal value.
     */
    public function deleteMultiple($keys);

    /**
     * Determines whether an item is present in the cache.
     *

     * NOTE: It is recommended that has() is only to be used for cache warming type purposes
     * and not to be used within your live applications operations for get/set, as this method
     * is subject to a race condition where your has() will return true and immediately after,
     * another script can remove it, making the state of your app out of date.
     *
     * @param string $key The cache item key.
     *
     * @return bool
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function has($key);
}

4. PhpPhpSpreadsheet에도 autoloader.php를 만든다. 
  

    - autoloader.php 
   

<?php

    spl_autoload_register(function ($class_name) {
        $preg_match = preg_match('/^PhpOffice\\\PhpSpreadsheet\\\/', $class_name);

        if (1 === $preg_match) {
            $class_name = preg_replace('/\\\/', '/', $class_name);
            $class_name = preg_replace('/^PhpOffice\\/PhpSpreadsheet\\//', '', $class_name);
            require_once(__DIR__ . '/../PhpSpreadsheet/' . $class_name . '.php');
        }
    });

 이제 최상위 폴더(PhpOffice의 상위 폴더)에 파일을 작성한 후 테스트 해본다. 

5. excel.php로 작성하였으며, 예제는 sample.xlsx이 사용되었고, 재고라는 시트명이 있는 파일이다. 

<?	 
    error_reporting(E_ALL); 
    ini_set("display_errors", 1);
    ini_set('memory_limit', -1); // 메모리 제한을 해제해준다. 


    use PhpOffice\PhpSpreadsheet\IOFactory;  
    
    require_once(__DIR__.'/PhpOffice/Psr/autoloader.php');
    require_once(__DIR__.'/PhpOffice/PhpSpreadsheet/autoloader.php');
  
    // 파일명 
    $inputFileName = __DIR__ . '/sample.xlsx';
 
    $spreadsheet = IOFactory::load($inputFileName);

    $Rows = $spreadsheet->getSheetByName('재고')->toArray(null, true, true, true);
   
?>
<table border=1>
<? 
     foreach($Rows as $row){
?>
    <tr>
        <? foreach($row as $col){ ?> 
            <td> <?=$col?></td>
        <? } ?> 
    
    </tr>
    
<? 
         
     }
    
?>
    
</table>
    

 

 

반응형