cwd
cwd

Reputation: 54776

How can I use PHP to get specific DOM nodes?

I can get all <a> tags using PHP's DOMDocument, but how can I get just the ones inside of the <ul> list? I tried $items->childNodes with no luck. Should I just switch to the PHP Simple HTML DOM Parser?

$string = '
<html>
<head>
</head>
    <body>

        <p>Please visit my site:
            <a href="http://mysite.com/">My Site</a>
        </p>

        <p>My friend's sites:</p>
        <ul>
            <a href="http://friend1.com/">Friend 1</a>
            <a href="http://friend2.com/">Friend 2</a>
            <a href="http://friend3.com/">Friend 3</a>
        </ul>

    </body>
</html>
';


$DOM = new DOMDocument;
@$DOM->loadHTML($string);

$items = $DOM->getElementsByTagName('a');

for ($i = 0; $i < $items->length; $i++){
    echo $items->item($i)->nodeValue;
    echo '<br />';
}

Upvotes: 1

Views: 103

Answers (1)

Calvin Froedge
Calvin Froedge

Reputation: 16373

Use xpath.

$xpath->query("//ul/a");

I've built pretty complex selectors using xpath. It's really powerful.

Upvotes: 1

Related Questions