Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: Parse string from html

I have opened an HTML file using

file_get_contents('http://www.example.com/file.html')

and want to parse the line including "ParseThis":

 <h1 class=\"header\">ParseThis<\/h1>

As you can see, it's within an h1 tag (the first h1 tag from the file). How can I get the text "ParseThis"?

like image 304
John Paneth Avatar asked Sep 19 '26 12:09

John Paneth


1 Answers

You can use DOM for this.

// Load remote file, supress parse errors
libxml_use_internal_errors(TRUE);
$dom = new DOMDocument;
$dom->loadHTMLFile('http://www.example.com/file.html');
libxml_clear_errors();

// use XPath to find all nodes with a class attribute of header
$xp = new DOMXpath($dom);
$nodes = $xp->query('//h1[@class="header"]');

// output first item's content
echo $nodes->item(0)->nodeValue;

Also see

  • Best methods to parse HTML
  • More examples by me with DOM.

Marking this CW because I have answered this before, but I am too lazy to find the duplicate

like image 120
2 revsGordon Avatar answered Sep 22 '26 02:09

2 revsGordon