메뉴 건너뛰기

tnt_lang

php/asp PHP로 문서의 HTML DOM을 손쉽게 가져오자~

구퍼 2008.08.14 10:50 조회 수 : 3002

http://simplehtmldom.sourceforge.net/

Easy Screen Scraping in PHP with the Simple HTML DOM Library


PHP를 이용해서 특정 웹문서의 HTML DOM을 손쉽게 가져올수 있는 라이브러리입니다.

온라인 document : http://simplehtmldom.sourceforge.net/manual.htm

문서는 다음과 같은 방법으로 가져옵니다.

직접 HTML string을 이용한 방법과 URL로의 접근, 그리고 local 문서로의 접근 이렇게 3가지의 방법이 있습니다.

// Create a DOM object from a string
$html = str_get_html('<html><body>Hello!</body></html>');

// Create a DOM object from a URL
$html = file_get_html('http://www.google.com/');

// Create a DOM object from a HTML file
$html = file_get_html('test.htm');



그리고


// Find all anchors, returns a array of element objects
$ret = $html->find('a');

// Find (N)th anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', 0);

// Find all <div> which attribute id=foo
$ret = $html->find('div[id=foo]');

// Find all <div> with the id attribute
$ret = $html->find('div[id]');

// Find all element has attribute id
$ret = $html->find('[id]');



이렇게 특정 엘리먼트를 발견할수 있고요.


엘리먼트의 속성을 가져올땐 이렇게


// Get a attribute ( If the attribute is non-value attribute (eg. checked, selected...), it will returns true or false)
$value = $e->href;

// Set a attribute(If the attribute is non-value attribute (eg. checked, selected...), set it's value as true or false)
$e->href = 'my link';

// Remove a attribute, set it's value as null!
$e->href = null;

// Determine whether a attribute exist?
if(isset($e->href))
        echo 'href exist!';




그리고 마음껏 DOM tree를 돌아다닐수도 있습니다.


// If you are not so familiar with HTML DOM, check this link to learn more...

// Example
echo $html->find("#div1", 0)->children(1)->children(1)->children(2)->id;
// or
echo $html->getElementById("div1")->childNodes(1)->childNodes(1)->childNodes(2)->getAttribute('id');



참 쉽죠?


무엇보다도 이걸 이용해서

RSS 제공하지 않는 곳의 게시물을 손쉽게 비공식 적으로 RSS로 발행할수 있을것 같습니다.

번호 제목 글쓴이 날짜 조회 수
78 JAVA - 한글 인코딩 변환 체크 한방에 끝내기 총관리자 2014.06.07 844
77 브라우저에서 JavaScript 실행 구퍼 2013.04.11 1570
76 clshoesfashionc4u nacyrobert 2013.03.15 1790
75 안드로이드 로그인 세션유지에 관한 연구 구퍼 2011.02.22 17444
74 "지금 보고 있는 웹페이지 창을 닫으려고 합니다..." 안나타나게 하기 file 구퍼 2010.07.30 11355
73 Allowed memory Error 처리 구퍼 2010.07.13 2177
72 경고메세지 없이 부모창 새로고침 하는법 구퍼 2010.01.14 2827
71 div display, visibility 속성구분 구퍼 2009.01.27 2256
» PHP로 문서의 HTML DOM을 손쉽게 가져오자~ file 구퍼 2008.08.14 3002
69 옥션처럼 실시간으로 남은시간 구하기 구퍼 2008.08.11 3505
68 정보를 다시 보내지 않으면....<익스플로러 MsgBox방지법>- mothod:post 하늘과컴 2007.10.13 3623
67 [struts]폼빈에 배열을 사용하기 박상현 2006.05.20 2312
66 윈도업데이트 이후 실행되지 않았던 activeX 컨트롤 실행 박상현 2005.11.16 2075
65 클래스 패스와 관련한 문제는 요 jsp 하나로.. 해결 끝이네요.. 하늘과컴 2005.11.15 2228
64 XMLHTTP설명 박상현 2005.11.11 2110
63 능동적으로 select box의 option값 설정및 삭제 박상현 2005.10.24 4087
62 테이블 소트 박상현 2005.08.18 1592
61 자바스크립트로 한글 , 초성 중성 종성 분리 (음소분리) 박상현 2005.05.19 4444
60 select box관련 함수들(입력, 수정, 삭제, 정렬등) 박상현 2004.09.23 3139
59 select box의 option값 정렬 함수 박상현 2004.09.23 5404
위로