user3467855 user3467855 - 6 months ago 12
PHP Question

Extracting text between html tags with multiple classes with DOM and XPATH

I am trying to extract text between 1 HTML tags but fail to do this:

HTML - Text to be extracted (http://www.alexa.com/siteinfo/google.com)

<span class="font-4 box1-r">3,757,209</span>


PHP

$data = frontend::file_get_contents_curl('http://www.alexa.com/siteinfo/'.$domain); // custom function that return the HTML string
$dom = new DOMDocument();
$dom->loadHTML(htmlentities($data));
$xpath = new DOMXpath($dom);
$backlinks = $xpath->query('//span[@class="font-4 box1-r"]/text()');
var_dump($backlinks); // returns null

Answer

The actual problem is due to htmlentities() escaping all tag delimiters (< and >), so you end up loading a long string with no elements and attributes to DOMDocument() :

$data = <<<HTML
<div><span class="font-4 box1-r">3,757,209</span></div>
HTML;
$doc = new DOMDocument();
$doc->loadHTML(htmlentities($data));
echo $doc->saveXML();

eval.in demo

output :

<?xml version="1.0" standalone="yes"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>&lt;div&gt;&lt;span class="font-4 box1-r"&gt;3,757,209&lt;/span&gt;&lt;/div&gt;</p></body></html>
Comments