Php: parse string from html

I opened the HTML file using

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

and want to parse a string, including "ParseThis":

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

As you can see, it is in the tag h1(the first tag h1from the file). How can I get the text "ParseThis"?

+3
source share
3 answers

You can use the 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 content
echo $nodes->item(0)->nodeValue;

Also see

Noting this CW because I answered it earlier, but I'm too lazy to find a duplicate

+5
source

Use this feature.

<?php
function get_string_between($string, $start, $end)
{
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0)
        return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}

$data = file_get_contents('http://www.example.com/file.html');

echo get_string_between($data, '<h1 class=\"header\">', '<\/h1>');
+4
source

h1, :

$doc = new DOMDocument();
$doc->loadHTML($html);
$h1 = $doc->getElementsByTagName('h1');
echo $h1->item(0)->nodeValue;

http://php.net/manual/en/class.domdocument.php

+1

Source: https://habr.com/ru/post/1762080/


All Articles