javascript escape 인코딩 php로 디코딩 하기

PHP/팁앱테크 2013. 1. 13. 10:26

// script /======================================================

< script >

var title;

title =escape("ㅇㄹㄴ#$#%2ㅇ,ㄹㅇ남; ㄹㅇㄴㅁ");

< /script >


// php /=========================================================

< ?php

function js_unescape($s) {

    $s= preg_replace('/%u(....)/', '&#x$1;', $s);

    $s= preg_replace('/%(..)/', '&#x$1;', $s);

    return html_entity_decode($s, ENT_COMPAT, 'utf-8');

}


$title = js_unescape($_REQUEST['title']);

? >

php 문서 안에 HTML 문서 쉽게 넣기

PHP/팁앱테크 2012. 6. 8. 11:02

php 문서에 html과 함께 코딩하는 경우가 많은데
이럴때 활용하면 가독성도 좋고 코딩하기 편합니다.

즉 템플릿 개념과 비슷하다고 볼 수 있겠죠

$string = <<<HTML
        < H3 >{$title}< /H3>
        < div >{$contents}
        HTML 소스를 편하고 보기좋게 넣을 수 있다
아주 좋아
HTML;

php5 simple xml을 이용한 xml 파싱 클래스

PHP/PHP5 클래스 2012. 5. 10. 13:57

php5 에서는 simpleXML 이라는 강력하고도 좋은 xml 클래스를 제공합니다.

이 클래스를 활용해서 보다 내가 원하는 형태로 데이타를 찾고

변환 할 수 있도록 클래스를 만듭니다.




#@ xml 파일 내용 /====================================


< ?xml version='1.0' encoding='UTF-8'? >
< main>
	< head>
		< title>타이틀< /title>
		< summary>써머리라고 하징< /summary>
	< /head>
	< navigation id="3000">
		< margin>30< /margin>
		< item title="메뉴1" image_off="" image_on="" />
		< item title="메뉴2" image_off="" image_on="" />
		< item title="메뉴3" image_off="" image_on="" />
		< item title="메뉴4" image_off="" image_on="" />
		< item title="메뉴5" image_off="" image_on="" />
		< item title="메뉴6" image_off="" image_on="" />
	< /navigation>
	< background>
		< image>< /image>
		< color>< /color>
	< /background>
< /main>




#@ php 클래스 선언 ----

< ?php
$sx =new XmlSimple($path.'/modules/main.xml');




#@ xml : head 데이타만 추출하기/==========================


$result=$sx->query('head');
$args1=$sx->fetch($result);
print_r($args1);

// 결과
Array
(
    [0] => Array
        (
            [title] => 타이틀
            [summary] => 써머리라고 하징
        )

)




#@ 네비게이션 메뉴 만 추출하기 /============================

$result=$sx->query('navigation');
$args1=$sx->fetch($result);
print_r($args1);

// 결과
Array
(
    [0] => Array
        (
            [attr] => Array
                (
                    [id] => 3000
                )

            [margin] => 30
            [item] => Array
                (
                    [0] => Array
                        (
                            [attr] => Array
                                (
                                    [title] => 메뉴1
                                    [image_off] => 
                                    [image_on] => 
                                )

                        )

                    [1] => Array
                        (
                            [attr] => Array
                                (
                                    [title] => 메뉴2
                                    [image_off] => 
                                    [image_on] => 
                                )

                        )

                    [2] => Array
                        (
                            [attr] => Array
                                (
                                    [title] => 메뉴3
                                    [image_off] => 
                                    [image_on] => 
                                )

                        )

                    [3] => Array
                        (
                            [attr] => Array
                                (
                                    [title] => 메뉴4
                                    [image_off] => 
                                    [image_on] => 
                                )

                        )

                    [4] => Array
                        (
                            [attr] => Array
                                (
                                    [title] => 메뉴5
                                    [image_off] => 
                                    [image_on] => 
                                )

                        )

                    [5] => Array
                        (
                            [attr] => Array
                                (
                                    [title] => 메뉴6
                                    [image_off] => 
                                    [image_on] => 
                                )

                        )

                )

        )

)


#@ 네비게이션 메뉴 중 item 값만 추출하기 /==================================

$result=$sx->query('navigation/item');
$args1=$sx->fetch($result);
print_r($args1);

// 결과
Array
(
    [0] => Array
        (
            [attr] => Array
                (
                    [title] => 메뉴1
                    [image_off] => 
                    [image_on] => 
                )

        )

    [1] => Array
        (
            [attr] => Array
                (
                    [title] => 메뉴2
                    [image_off] => 
                    [image_on] => 
                )

        )

    [2] => Array
        (
            [attr] => Array
                (
                    [title] => 메뉴3
                    [image_off] => 
                    [image_on] => 
                )

        )

    [3] => Array
        (
            [attr] => Array
                (
                    [title] => 메뉴4
                    [image_off] => 
                    [image_on] => 
                )

        )

    [4] => Array
        (
            [attr] => Array
                (
                    [title] => 메뉴5
                    [image_off] => 
                    [image_on] => 
                )

        )

    [5] => Array
        (
            [attr] => Array
                (
                    [title] => 메뉴6
                    [image_off] => 
                    [image_on] => 
                )

        )

)
? >




#@ simple xml 를 이용해 데이타 배열로 리턴해 주는 클래스 소스 /==============================

< ?php
class XmlSimple
{
	public $xml_obj;
	private $num_rows = 0;	# query 엘리멘트 갯수

	#@ void
	# xpath = xml 파일 경로
	public function __construct($xpath){
		if(!self::isExists($xpath))
				throw new ErrorException('파일이 없어 어데간겨 잘 찾아봐',__LINE__);

		# 데이타 가져오기
		if(!$xml_data = file_get_contents($xpath))
				throw new ErrorException('No data',__LINE__);

		# simple xml
		$this->xml_obj = new SimpleXMLElement($xml_data);
	}

	#@ return xml array
	# navigation/item
	public function query($query){
		$result=$this->xml_obj->xpath($query);
		$this->num_rows =count($result);
	return $result;
	}

	#@return array
	public function fetch($result)
	{
		$loop =array();
		for($i=0; $i<$this->num_rows; $i++)
		{
			// attributes만 있을 수 있음
			$attr_count=count($result[$i]->attributes());
			if($attr_count>0)	{
				$loop2=&$loop[$i]['attr'];
				foreach($result[$i]->attributes() as $k2=>$kv){
					$loop2[$k2]=strval($kv);
				}
			}

			// child
			if(count($result[$i])){
				foreach($result[$i] as $k=>$v)
				{				
					// child -> attributes
					$attr_count=count($v->attributes());
					if($attr_count>0)	{
						$loop3=&$loop[$i][$k][]['attr'];
						foreach($v->attributes() as $k3=>$k3v){
							$loop3[$k3]=strval($k3v);
						}
					}else{
						$loop[$i][$k]=strval($v);
					}
				}
			}
		}
	return $loop;
	}

	#@ return
	public function __get($propertyName){
		if(property_exists(__CLASS__,$propertyName)){
			return $this->{$propertyName};
		}
	}

	# 로컬 파일인지 체크
	protected function isExists($filename){
		if(!file_exists($filename)) return false;
	return true;
	}
}
 ? >


PHP5 Exception 예외처리 사용 방법과 그 종류

PHP/PHP5 클래스 2012. 4. 3. 22:18

PHP5 Exception 사용 방법과 그 종류


Exception 종류 클래스1

BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
LogicException
OutOfBoundsException
OutOfRangeException
OverflowException
RangeException
RuntimeException
UnderflowException
UnexpectedValueException


Exception 종류 클래스 2
Exception
ErrorException




@ 가장 많이 쓰는 Exception 클래스 소스

Exception {
    /* 프로퍼티 */
   protected string $Exception->message ;
   protected int $code ;
   protected string $file ;
   protected int $line ; 


   /* 메소드 */
   public Exception::__construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
   final public string Exception::getMessage ( void )
   final public Exception Exception::getPrevious ( void )
   final public mixed Exception::getCode ( void )
   final public string Exception::getFile ( void )
   final public int Exception::getLine ( void )
   final public array Exception::getTrace ( void )
   final public string Exception::getTraceAsString ( void )
   public string Exception::__toString ( void )
   final private void Exception::__clone ( void )
}

@ 사용법

/*방법 1*/
try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}


/*방법 2*/
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    else return 1/$x;
}


/* 방법 3 */
class Test{
      public init($s){
           if(!empty($s)) 
                 throw new Exception('Division by zero.');
      }
}




PHP 제어 구문과 문법

PHP/팁앱테크 2012. 4. 3. 21:54

PHP의 다양한 제어 구문과 문법을 알아 보겠습니다.


1. IF 문

Noteelseif와 else if은 위 예제처럼 대괄호를 사용할 때 정확히 같은 구문으로 간주됩니다. if/elseif 조건을 콜론을 사용해서 정의할 때, else if 처럼 두 단어로 나눠서는 안됩니다. PHP는 처리 오류로 실패합니다.

/* 방법1 */
if($a > $b):
    echo $a." is greater than ".$b;
elseif ($a == $b) : // 단어가 붙어 있어야 함.
    echo $a." equals ".$b;
else:
    echo $a." is neither greater than or equal to ".$b;
endif;

/*방법2*/
$hour = 11;
echo $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!";


2. if 안의 if문 일때

if($a):
    echo $a;
    if($b) {
      echo $b;
    }; // <- closing semicolon
else:
    echo $c;
endif;



3. while 문

/* example 1 */
$i = 1;
while ($i <= 10) {
    echo $i++;
}

/* example 2 */
$i = 1;
while ($i <= 10):
    echo $i;
    $i++;
endwhile;


4. for 문
/* 예제 1 */
for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

/* 예제 2 */
for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i;
}

/* 예제 3 */
$i = 1;
for (; ; ) {
    if ($i > 10) {
        break;
    }
    echo $i;
    $i++;
}

/* 예제 4 */
for ($i = 1, $j = 0; $i <= 10; $j += 1, print $i, $i++);


/* 예제 5 */
for ($i = 1; $i <= 10; $i++):
    echo $i;
endfor;

5. switch 문

/*예제 1*/
switch ($i) {
case 0:
    echo "i는 0과 같다";
    break;
case 1:
    echo "i는 1과 같다";
    break;
case 2:
    echo "i는 2와 같다";
    break;
default:
    echo "i는 0, 1, 2 어느것도 아니다";
}

/* 예제 2 */
switch ($i):
case 0:
    echo "i equals 0";
    break;
case 1:
    echo "i equals 1";
    break;
case 2:
    echo "i equals 2";
    break;
default:
    echo "i is not equal to 0, 1 or 2";
endswitch;


6. foreach 문

$arr = array("하나", "둘", "셋");

/*방법1*/
foreach ($arr as $key => $value) {
    echo "키: $key; 값: $value
\n"; } /*방법2*/ foreach ($arr as $key => $value) : echo "키: $key; 값: $value"; endforeach;