QueryPath HTML 처리 예제 3

QueryPath HTML 처리 예제 3

1 예제 코드[ | ]

<?php
require '/var/www/phplib/QueryPath2/QueryPath.php';
function xmp_print($arr) { echo '<xmp>'; print_r($arr); echo '</xmp>'; }

function node2arr($node) {
	$ret = array();
	$ret['tag'] = utf8_decode($node->tag());
	$ret['attr'] = array_map('utf8_decode', $node->attr());
	$ret['text'] = utf8_decode($node->text());
	$ret['innerhtml'] = utf8_decode2($node->innerhtml());
	$ret['html'] = utf8_decode2($node->html());
	return $ret;
}

function utf8_decode2($str) {
	$str = utf8_decode($str);
	$str = htmlchars2utf($str);
	return $str;
}

function htmlchars2utf($str) {
    $convmap = array(0x0, 0x2FFFF, 0, 0xFFFF);
    return mb_decode_numericentity($str, $convmap, 'UTF-8');
}

$html = '<!DOCTYPE html>
<html>
	<head>
		<title>예제</title>
	</head>
	<body> 
		<p class="a" id="test1">다람쥐 헌 쳇바퀴<br>타고파.</p>
		<p class="a" id="test2">다람쥐가노래를한<b>다</b>
		람쥐.</p>
		<p>다람쥐</p>
	</body>
</html>';

$children = htmlqp($html, 'body', array('convert_to_encoding' => 'utf-8'))->children('p.a');
foreach($children as $child) {
	$node = node2arr($child);
	xmp_print($node);
}

2 실행 결과[ | ]

Array
(
    [tag] => p
    [attr] => Array
        (
            [class] => a
            [id] => test1
        )

    [text] => 다람쥐 헌 쳇바퀴타고파.
    [innerhtml] => 다람쥐 헌 쳇바퀴<br/>타고파.
    [html] => <p class="a" id="test1">다람쥐 헌 쳇바퀴<br/>타고파.</p>
)
Array
(
    [tag] => p
    [attr] => Array
        (
            [class] => a
            [id] => test2
        )

    [text] => 다람쥐가노래를한다
		람쥐.
    [innerhtml] => 다람쥐가노래를한<b>다</b>
		람쥐.
    [html] => <p class="a" id="test2">다람쥐가노래를한<b>다</b>
		람쥐.</p>
)

3 같이 보기[ | ]

4 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}