piterskiy

PHP Simple HTML DOM Parser

Nov 2nd, 2017
25,759
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.21 KB | None | 0 0
  1. PHP Simple HTML DOM Parser
  2. http://simplehtmldom.sourceforge.net/
  3.  
  4. -------------
  5.  
  6. // Create DOM from URL or file
  7. $html = file_get_html('http://www.google.com/');
  8.  
  9. // Find all images
  10. foreach($html->find('img') as $element)
  11.        echo $element->src . '<br>';
  12.  
  13. // Find all links
  14. foreach($html->find('a') as $element)
  15.        echo $element->href . '<br>';
  16.  
  17. -------------
  18.  
  19. // Create DOM from string
  20. $html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
  21.  
  22. $html->find('div', 1)->class = 'bar';
  23.  
  24. $html->find('div[id=hello]', 0)->innertext = 'foo';
  25.  
  26. echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>
  27.  
  28. -------------
  29.  
  30. // Dump contents (without tags) from HTML
  31. echo file_get_html('http://www.google.com/')->plaintext;
  32.  
  33. -------------
  34.  
  35. // Create DOM from URL
  36. $html = file_get_html('http://slashdot.org/');
  37.  
  38. // Find all article blocks
  39. foreach($html->find('div.article') as $article) {
  40.     $item['title']     = $article->find('div.title', 0)->plaintext;
  41.     $item['intro']    = $article->find('div.intro', 0)->plaintext;
  42.     $item['details'] = $article->find('div.details', 0)->plaintext;
  43.     $articles[] = $item;
  44. }
  45.  
  46. print_r($articles);
Advertisement
Add Comment
Please, Sign In to add comment