Search HTML document in PHP

I am trying to use DOMDocument and XPath to search for an HTML document using PHP. I want to search by a number, for example "022222", and it should return the value of the corresponding h2 tag. Any thoughts on how this will be done?

HTML document can be found at http://pastie.org/1211369

+3
source share
2 answers

How about this?

$sxml = simplexml_load_string($data);
$find = "022222";

print_r($sxml->xpath("//li[.='".$find."']/../../../div[@class='content']/h2"));

It returns:

Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => Item 2
        )

)

//li[.='xxx']will find liyour search. Then we use ../to increase the three levels before we go down to the content-div, as indicated div[@class='content']. Finally, we select the child h2.

Just FYI, here's how to do it using the DOM:

$dom = new DOMDocument();
$dom->loadXML($data);

$find = "022222";

$xpath = new DOMXpath($dom);
$res = $xpath->evaluate("//li[.='".$find."']/../../../div[@class='content']/h2");

if ($res->length > 0) {
    $node = $res->item(0);
    echo $node->firstChild->wholeText."\n";
}
+2
I want to search by a number such as '022222', and it should return the value of the corresponding h2 tag. Any thoughts on how this would be done?

The HTML document can be found at http://pastie.org/1211369

XML XHtml XPath.

inan <html>.

XML XPath, node,:

/*/div[div/ul/li = '022222']/div[@class='content']/h2/text()

XPath , , .

XML-, XPath, :

<html>
 <div class="item">
    <div class="content"><h2>Item 1</h2></div>
    <div class="phone">
        <ul class="phone-single">
            <li>01234 567890</li>
        </ul>
    </div>
 </div>

 <div class="item">
    <div class="content"><h2>Item 2</h2></div>
    <div class="phone">
        <ul class="phone-multiple">
        <li>022222</li>
            <li>033333</li>
        </ul>
    </div>
 </div>

 <div class="item">
    <div class="content"><h2>Item 3</h2></div>
    <div class="phone">
        <ul class="phone-single">
            <li>02345 678901</li>
        </ul>
    </div>
 </div>

 <div class="item">
    <div class="content"><h2>Item 4</h2></div>
    <div class="phone">
        <ul class="phone-multiple">
            <li>099999999</li>
            <li>088888888</li>
        </ul>
    </div>
 </div>
</html>
+2

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


All Articles