백엔드 개발 PHP 튜토리얼 基于simple_html_dom的使用小结_php技巧

基于simple_html_dom的使用小结_php技巧

May 17, 2016 am 08:57 AM
dom html simple

复制代码 代码如下:

简单范例
$html = file_get_html('http://www.google.com/');  //获取html$dom = new simple_html_dom();    //new simple_html_dom对象$dom->load($html)      //加载html// Find all images foreach($dom->find('img') as $element) {   //获取img标签数组       echo $element->src . '
';    //获取每个img标签中的src}// Find all links foreach($dom->find('a') as $element){    //获取a标签的数组       echo $element->href . '
';    //获取每个a标签中的href}


$html = file_get_html('http://slashdot.org/');   //获取html$dom = new simple_html_dom();    //new simple_html_dom对象$dom->load($html);     //加载html// Find all article blocksforeach($dom->find('div.article') as $article) {       $item['title']     = $article->find('div.title', 0)->plaintext; //plaintext 获取纯文本    $item['intro']    = $article->find('div.intro', 0)->plaintext;    $item['details'] = $article->find('div.details', 0)->plaintext;    $articles[] = $item;}print_r($articles);

}


// Create DOM from string

$html = str_get_html('

Hello
World
');
$dom = new simple_html_dom();     //new simple_html_dom对象

$dom->load($html);      //加载html
$dom->find('div', 1)->class = 'bar';    //class = 赋值 给第二个div的class赋值

$dom->find('div[id=hello]', 0)->innertext = 'foo';   //innertext内部文本

echo $dom;

// Output:

foo
World

 

DOM methods & properties
Name Description
void __construct ( [string $filename] ) 构造函数,将文件名参数将自动加载内容,无论是文本或文件/ url。
 string plaintext 纯文本
void clear () 清理内存
void load ( string $content ) 加载内容
string save ( [string $filename] ) Dumps the internal DOM tree back into a string. If the $filename is set, result string will save to file.
void load_file ( string $filename ) Load contents from a from a file or a URL.
void set_callback ( string $function_name ) 设置一个回调函数。
mixed find ( string $selector [, int $index] ) 找到元素的CSS选择器。返回第n个元素对象如果索引设置,否则返回一个数组对象。


 4.find 方法详细介绍


find ( string $selector [, int $index] )
// Find all anchors, returns a array of element objects a标签数组
$ret = $html->find('a');

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

// Find lastest anchor, returns element object or null if not found (zero based)最后一个a标签
$ret = $html->find('a', -1);

// Find all

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

// Find all

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


// Find all element which id=foo
$ret = $html->find('#foo');

// Find all element which class=foo
$ret = $html->find('.foo');

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

// Find all anchors and images a标签与img标签数组
$ret = $html->find('a, img'); 

// Find all anchors and images with the "title" attribute
$ret = $html->find('a[title], img[title]');


// Find all

  • in

      $es = $html->find('ul li'); ul标签下的li标签数组

      // Find Nested

      tags
      $es = $html->find('div div div');  div标签下div标签下div标签数组

      // Find all

      in which class=hello
      $es = $html->find('table.hello td'); table标签下td标签数组

      // Find all td tags with attribite align=center in table tags
      $es = $html->find(''table td[align=center]');

       5.Element  的方法
      $e = $html->find("div", 0);                              //$e 所拥有的方法如下表所示
      Attribute Name Usage
      $e->tag 标签
      $e->outertext 外文本
      $e->innertext 内文本
      $e->plaintext 纯文本

       

      // Example
      $html = str_get_html("

      foo bar
      ");
      echo $e->tag; // Returns: " div"
      echo $e->outertext; // Returns: "
      foo bar
      "
      echo $e->innertext; // Returns: " foo bar"
      echo $e->plaintext; // Returns: " foo bar"

      6.DOM traversing 方法
      Method Description
      mixed$e->children ( [int $index] ) 子元素
      element$e->parent () 父元素
      element$e->first_child () 第一个子元素
      element$e->last_child () 最后一个子元素
      element$e->next_sibling () 后一个兄弟元素
      element$e->prev_sibling () 前一个兄弟元素


      // 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');


  • 본 웹사이트의 성명
    본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

    핫 AI 도구

    Undresser.AI Undress

    Undresser.AI Undress

    사실적인 누드 사진을 만들기 위한 AI 기반 앱

    AI Clothes Remover

    AI Clothes Remover

    사진에서 옷을 제거하는 온라인 AI 도구입니다.

    Undress AI Tool

    Undress AI Tool

    무료로 이미지를 벗다

    Clothoff.io

    Clothoff.io

    AI 옷 제거제

    AI Hentai Generator

    AI Hentai Generator

    AI Hentai를 무료로 생성하십시오.

    인기 기사

    R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
    3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. 최고의 그래픽 설정
    3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
    3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

    뜨거운 도구

    메모장++7.3.1

    메모장++7.3.1

    사용하기 쉬운 무료 코드 편집기

    SublimeText3 중국어 버전

    SublimeText3 중국어 버전

    중국어 버전, 사용하기 매우 쉽습니다.

    스튜디오 13.0.1 보내기

    스튜디오 13.0.1 보내기

    강력한 PHP 통합 개발 환경

    드림위버 CS6

    드림위버 CS6

    시각적 웹 개발 도구

    SublimeText3 Mac 버전

    SublimeText3 Mac 버전

    신 수준의 코드 편집 소프트웨어(SublimeText3)

    HTML의 테이블 테두리 HTML의 테이블 테두리 Sep 04, 2024 pm 04:49 PM

    HTML의 테이블 테두리 안내. 여기에서는 HTML의 테이블 테두리 예제를 사용하여 테이블 테두리를 정의하는 여러 가지 방법을 논의합니다.

    HTML의 중첩 테이블 HTML의 중첩 테이블 Sep 04, 2024 pm 04:49 PM

    HTML의 Nested Table에 대한 안내입니다. 여기에서는 각 예와 함께 테이블 내에 테이블을 만드는 방법을 설명합니다.

    HTML 여백-왼쪽 HTML 여백-왼쪽 Sep 04, 2024 pm 04:48 PM

    HTML 여백-왼쪽 안내. 여기에서는 HTML margin-left에 대한 간략한 개요와 코드 구현과 함께 예제를 논의합니다.

    HTML 테이블 레이아웃 HTML 테이블 레이아웃 Sep 04, 2024 pm 04:54 PM

    HTML 테이블 레이아웃 안내. 여기에서는 HTML 테이블 레이아웃의 값에 대해 예제 및 출력 n 세부 사항과 함께 논의합니다.

    HTML 정렬 목록 HTML 정렬 목록 Sep 04, 2024 pm 04:43 PM

    HTML 순서 목록에 대한 안내입니다. 여기서는 HTML Ordered 목록 및 유형에 대한 소개와 각각의 예에 대해서도 설명합니다.

    HTML에서 텍스트 이동 HTML에서 텍스트 이동 Sep 04, 2024 pm 04:45 PM

    HTML에서 텍스트 이동 안내. 여기서는 Marquee 태그가 구문과 함께 작동하는 방식과 구현할 예제에 대해 소개합니다.

    HTML 입력 자리 표시자 HTML 입력 자리 표시자 Sep 04, 2024 pm 04:54 PM

    HTML 입력 자리 표시자 안내. 여기서는 코드 및 출력과 함께 HTML 입력 자리 표시자의 예를 논의합니다.

    PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? Feb 07, 2025 am 11:57 AM

    이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

    See all articles