Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get value of <h2> of html page with PHP DOM?

Tags:

php

I have a var of a HTTP (craigslist) link $link, and put the contents into $linkhtml. In this var is the HTML code for a craigslist page, $link.

I need to extract the text between <h2> and </h2>. I could use a regexp, but how do I do this with PHP DOM? I have this so far:

$linkhtml= file_get_contents($link);
$dom = new DOMDocument;
@$dom->loadHTML($linkhtml);

What do I do next to put the contents of the element <h2> into a var $title?

like image 252
Matt Avatar asked Feb 21 '23 13:02

Matt


1 Answers

if DOMDocument looks complicated to understand/use to you, then you may try PHP Simple HTML DOM Parser which provides the easiest ever way to parse html.

require 'simple_html_dom.php';
$html = '<h1>Header 1</h1><h2>Header 2</h2>';
$dom = new simple_html_dom();
$dom->load( $html );
$title = $dom->find('h2',0)->plaintext; 
echo $title; // outputs: Header 2
like image 119
Varol Avatar answered Mar 05 '23 11:03

Varol