Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching an HTML document in PHP

I'm trying to use DOMDocument and XPath to search an HTML document using PHP. 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

like image 699
RichW Avatar asked Sep 05 '26 15:09

RichW


1 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 locate the li your searching for. Then we use ../ to step up three levels, before we descend into the content-div, as specified by div[@class='content']. Finally we choose the h2 child.

Just FYI, here's how to do it using 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";
}
like image 92
Emil H Avatar answered Sep 08 '26 04:09

Emil H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!