일상/일상 관련

PHP 핵심정리 2/2

by 소서리스25 2023. 4. 7.
반응형

 

PHP 핵심정리 2/2 - 펌 자료

 

[mb_detect_encoding Utf-8/Euc-Kr 확인]

 

넘어온 문자가 utf-8인가 euc-kr인가 체크해야할 필요가 있다.

그 방법으로 다음의 방법이 있다고 한다.

 

1
2
3
4
5
6
7
8
9
 
$ary[] = “UTF-8″;
 
$ary[] = “EUC-KR”;
 
$ary[] = “ASCII”;
 
mb_detect_encoding($id, $ary);
 
cs

[array 관련. usort와 uasort의 차이]

reset : 배열의 내부 포인터를 첫 원소로 설정

rsort : 역순으로 배열 정렬

shuffle : 배열을 섞습니다

 

sort : 배열 정렬

uasort : 사용자 정의 비교 함수로 배열을 정렬하고 인덱스 연관성을 유지

uksort : 사용자 정의 비교 함수를 사용하여 키에 의한 배열 정렬

usort : 사용자 정의 비교 함수를 사용하여 값에 의한 배열 정렬

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
 
<?phpfunction my_usort($c$d)
{
    if ($c == $dreturn 0;
 
    return ($c > $d) ? -1 : 1;
}
 
 
$names = array(“Tahreem”, “Rizwan”,”Sadia”, “Mahim”,”Anwar”, “Misbah”);
usort($names, “my_usort”);
 
print_r ($names);
 
echo “<br/>?????????<br/>”;
 
function usort_function($x$y)
{
    if ($x == $y)
        return 0;
    else if ($x > $y)
        return 1;
    else
        return -1;
}
 
 
 
$num = array(45,35,68,58,41);
 
usort($num , ‘usort_function’);
 
print_r($num); 
 
echo “<br/>”;
 
foreach($num as $key => $value)
{
    echo “$key: $value<br/>”;
}
 
echo “<br/>?????????<br/>”;
 
function uasort_function($x$y)
{
    if ($x == $y)
        return 0;
    else if ($x > $y)
        return 1;
    else
        return -1;
}
 
 
$num = array(45,35,68,58,41);
 
usort($num , ‘usort_function’);
 
print_r($num); 
 
echo “<br/>”;
 
foreach($num as $key => $value)
{
    echo “$key: $value<br/>”;
}
 
echo “<br/>?????????<br/>”;
 
function my_sort($x$y)
{
    if ($x == $yreturn 0;
 
    return ($x > $y) ? -1 : 1;
}
 
 
$people = array(“10″ => “javascript”, “20” => “php”, “60” => “vbscript”, “40” => “jsp”);
 
usort($people, “my_sort”);
 
print_r($people);
 
echo “<br/>?????????<br/>”;
 
$people1 = array(“10″ => “javascript”, “20” => “php”, “60” => “vbscript”, “40” => “jsp”);
 
uasort($people1, “my_sort”);
 
print_r ($people1);
 
 
?>
cs

 

[PHP 주의점]

 

정수형, 실수형(double), 문자열, 불리언, 객체, NULL, resource

 

$totalamount = (double)$totalqty;

$$varname

define(‘PRICE’, 100)

 

변수의 범위

수퍼글로벌 변수는 스크립트 전역에서 사용할 수 있다.

한 번 선언된 상수는 스크립트 전역에서 사용할 수 있다. 즉 함수 안과 밖 모두에서 사용할 수 있다.

전역 변수는 스크립트 내에서 정의된 변수로 스크립트 내에서 사용할 수 있지만 함수 안에서는 사용할 수 없다.

함수 안에서 정의된 변수는 함수 내에서만 사용할 수 있다.

함수 안에서 전역으로 정의된 변수는 함수 밖에서는 사용할 수 없지만 매 사용 시마다 값이 저장되어 다음에 사용할 수 있다.

함 수 안에서 사용된 변수는 함수가 끝나면 삭제된다.

 

수퍼글로벌 변수는 함수 안과 밖 모두에서 사용할 수 있다.

$GLOBALS : 모든 전역변수를 담고 있는 배열 (global 키워드를 통해 변수를 사용 가능함. 또한 $GLOBALS['myvariable'] 과 같이도 사용가능.)

$_SERVER

$_GET

$_POST

$_COOKIE

$_FILES

$_ENV

$_REQUEST : $_GET, $_POST, $_COOKIE 를 포함. PHP4.3.0 이후부터는 $_FILES는 포함하지 않음.

$_SESSION

 

$a = @(57/0); // @가 없다면 오류가 나지만, @가 있으면 오류를 그냥 다음으로 넘어감.

만약 php.ini 에서 track_errors 를 설정해놓았다면 $php_errormsg 라는 전역변수에 오류메시지를 저장한다.

 

실행연산자(execution operator) : “ 사이에 서버의 커맨드라인 명령어를 입력하여 사용할 수 있다. 결과값이 표현식의 리턴값이 된다.

 

1
2
3
4
5
6
7
8
9
 
$out = `ls -la`;
 
echo ‘<pre>’.$out.'</pre>';
 
$out = `dir c:`;
 
echo ‘<pre>’.$out.'</pre>';
 
cs

 

배열 연산자

$a + $b : 합집함.

$a == $b : 같은 요소를 가지고 있으면 true 반환. !=, <>

$a === $b : 같은 순서로 같은 요소를 가지고 있으면 true 반환. !==

 

형 연산자 (instanceof)

class sampleClass{};

$myObject = new sampleClass();

if($myObject instanceof sampleClass)

echo “myObject is an instance of sampleClass”;

 

print 는 복잡한 표현식 안에서 출력을 생성할 때 사용하지만 보통 echo 보다 느리다.

 

number_format($totalamount, 2) : 소수점 이하 두자리 숫자.

 

gettype(), settype()

bool, int, double, string, array, object, resource, NULL 표준형이 아닐 경우 unknown type을 반환한다.

다양한 형을 받아들일 수 있는 인자의 경우 mixed. 실제로 이런 형은 없다. 그냥 보기 표현하기 위해서임.

 

is_array() : 배열인지 검사.

is_double(), is_float(), is_real() : 부동소수점형인지 검사.

is_long(), is_int(), is_integer() : 정수형인지 검사.

is_string() : 문자열인지 검사.

is_bool() : 불리언형인지 검사.

is_object() : 객체형인지 검사.

is_resource() : resource 형인지 검사.

is_null() : null 인지 검사

is_scalar() : 정수형, 불리언형, 문자열이나 실수형인지 검사.

is_numeric() : 숫자 혹은 숫자 문자열인지 검사.

is_callable() : 변수에 저장된 값이 호출할 수 있는 함수의 이름인지 검사.

 

isset() : 변수가 존재하면 true. 콤마를 구분자로 사용하여 다수의 변수를 넣어주었을 때 모든 변수가 존재해야 true 반환.

unset()

empty() : 변수가 존재하고, 비어있지 않으며, 0이 아닌값을 가지고 있다면 false, 아니면 true. 배열의 경우 array(”) empty가 아니다. array() empty .

 

 

[1주일전 구하기, 지난주, 이번주, 다음주 구하기 php]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 
* 1주일전 구하기
 
*/
 
 
 
echo date(‘Y-m-d’, strtotime(“-1 week”));// 1주전(현재일 기준)
 
echo date(‘Y-m-d’, strtotime(“-1 week”, mktime(0, 0, 0, 06, 06, 2011)));// 1주전 (특정일 기준)
 
 
 
/**
 
* 지난주, 이번주, 다음주 구하기
 
*/
 
 
 
$today = time();
 
$week = date(“w”);
 
$week_first= $today-($week*86400);
 
$week_last = $week_first+(6*86400);
 
$last_week = date(“Y-m-d”, $week_first ? (86400*7)).” ~ “.date(“Y-m-d”, $week_last-(86400*7)); //지난주
 
$now_week = date(“Y-m-d”, $week_first).” ~ “.date(“Y-m-d”, $week_last);//이번주
 
$next_week = date(“Y-m-d”, $week_first + (86400*7)).” ~ “.date(“Y-m-d”, $week_last+(86400*7)); //다음주
 
cs

 

 

[Php에서 Outlook 프로그래밍 Outlook.Application]

 

1
2
3
4
5
6
7
8
9
10
<?php
    $objApp = new COM(“Outlook.Application”);
    $myItem = $objApp->CreateItem(olMailItem);
    $a=$myItem->Recipients->Add(“admin@purplerain.org”);
    $myItem->Subject=”Subject”;
    $myItem->Body=”This is a Body Section now…..!”;
    $myItem->Display();
    $myItem->Send();
?>
 
cs

 

[PHP, Phpexcel Php로 엑셀 파일 읽고 쓰기]

 

 - PHP로 실제 엑셀 파일을 생성하고, 엑셀 파일을 읽는 방법

 

 

 1. 간단한 엑셀 파일 생성

 

 - HTML table로 표를 만들어서 헤더만 엑셀로 전송하는 것이 일반적인 추세

1
2
3
4
5
6
7
8
9
 
if($_GET['mode']==’excel’)
{
    header( ‘Content-type: application/vnd.ms-excel’ );
    header( ‘Content-Disposition: inline; filename=”listall_’.date(‘Ymd’).’.xls”‘ );
    header( ‘Content-Description: sitePHPbasic Generated Data’ );
    $dbinfo['skin']=’excel';
}
 
cs

 

 

2. PHPEXCELhttp://phpexcel.codeplex.com/

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    
include_once ‘Classes/PHPExcel.php';
include_once ‘Classes/PHPExcel/IOFactory.php';
$filename = ‘./1.xls';
try 
{
    // 업로드 된 엑셀 형식에 맞는 Reader객체를 만든다.
    $objReader = PHPExcel_IOFactory::createReaderForFile($filename);
    // 읽기전용으로 설정
    $objReader->setReadDataOnly(true);
    // 엑셀파일을 읽는다
    $objExcel = $objReader->load($filename);
    // 첫번째 시트를 선택
    $objExcel->setActiveSheetIndex(0);
    $objWorksheet = $objExcel->getActiveSheet();
    echo “<table>”;
    $rowIterator = $objWorksheet->getRowIterator();
    foreach ($rowIterator as $row) // 모든 행에 대해서
    { 
        echo “<tr>”;
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(false);
        
        foreach ($cellIterator as $cell) // 해당 열의 모든 셀에 대해서
        { 
            echo “<td>”,$cell->getValue(), “</td>”;
        }        
        
        echo “<tr>”;
    }
    /*
    $maxRow = $objWorksheet->getHighestRow();
    for ($i = 2 ; $i <= $maxRow ; $i++) // 두번째 행부터 읽는다
    { 
        $no = $objWorksheet->getCell(‘A’ . $i)->getValue(); // 첫번째 열
        $name = $objWorksheet->getCell(‘B’ . $i)->getValue(); // 두번째 열
        $phone = $objWorksheet->getCell(‘C’ . $i)->getValue(); // 세번째 열
    }
    */
    echo “</table>”;
}
catch (exception $e) 
{
    echo ‘엑셀파일을 읽는도중 오류가 발생하였습니다.';
}
cs

 

 

3. Pear Excel


php-pear-excel-0.8-1.1.el3.rf.noarch.rpm
php-pear-ole-0.5-2.1.el3.dag.noarch.rpm

 

 

4. HTML 엑셀로 간단하게 만들자

1
2
3
4
5
6
7
8
9
10
<?
    header(” Content-Type: application/vnd.ms-excel; charset=euc-kr”);
    header( “Content-Disposition: attachment; filename=excel.xls” );
    header( “Content-Description: PHP4 Generated Data” );
?>
 
< table><tr>
< td style=mso-number-format:’@’></td>
< /tr></table>
 
cs

 

MSO FORMAT(mso-number-format) 종류
mso-number-format:@
text : 문자서식
mso-number-format:”0.000″
3 decimals : 소수점 3자리까지 서식
mso-number-format:#,##0.000
comma separators (and 3 decimals) : 소수점 3자리까지 서식 & [,] 3자리 끊어서 서식
mso-number-format:”mm/dd/yy”
Date format : 날짜 서식
mso-number-format:”d\-mmm\-yyyy”
another date format : 날짜 서식
mso-number-format:Percent
(percent) : % 서식
mso-number-format:”0″ No Decimals
mso-number-format:”0.00″ 2 Decimals
mso-number-format:”mm/dd/yy” Date format
mso-number-format:”m/d/yy h:mm AM/PM” D -T AMPM
mso-number-format:”Short Date” 05/06/-2008
mso-number-format:”Medium Date” 05-jan-2008
mso-number-format:”Short Time” 8:67
mso-number-format:”Medium Time” 8:67 am
mso-number-format:”Long Time” 8:67:25:00
mso-number-format:”Percent” Percent ? two decimals
mso-number-format:”0.E+00″ Scientific Notation
mso-number-format:”@” Text
mso-number-format:”# ???/???” Fractions ? up to 3 digits (312/943)
mso-number-format:”022?022#,##0.00″ ?12.76
mso-number-format:”#,##0.00_ ;[Red]-#,##0.00 ” 2 decimals, negative numbers in red and signed (1.86 -1.66)
mso-number-format:”\#\,\#\#0\.00_\)\;\[Black\]\\(\#\,\#\#0\.00\\)” Accounting Format ?5,(5)

 

 

반응형

댓글