Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOMXpath - Get href attribute and text value of an a element

So I have a HTML string like this:

<td class="name">
   <a href="/blah/somename23123">Some Name</a>
</td>
<td class="name">
   <a href="/blah/somename28787">Some Name2</a>
</td>

Using XPath I'm able to get value of href attribute using this Xpath query:

 $domXpath = new \DOMXPath($this->domPage);
 $hrefs = $domXpath->query("//td[@class='name']/a/@href");
 foreach($hrefs as $href) {...}

And It's even easier to get a text value, like this:

 // Xpath auto. strips any html tags so we are 
 // left with clean text value of a element
 $domXpath = new \DOMXPath($this->domPage);
 $names = $domXpath->query("//td[@class='name']/");
 foreach($names as $name) {...}

Now I'm curious to know, how can I combine those two queries to get both values with only one query (If it's something like that even posible?).

like image 429
Marko Jovanović Avatar asked Jul 25 '11 18:07

Marko Jovanović


2 Answers

Fetch

//td[@class='name']/a

and then pluck the text with nodeValue and the attribute with getAttribute('href').

Apart from that, you can combine Xpath queries with the Union Operator | so you can use

//td[@class='name']/a/@href|//td[@class='name']

as well.

like image 113
Gordon Avatar answered Nov 14 '22 15:11

Gordon


To reduce the code to a single loop, try:

$anchors = $domXpath->query("//td[@class='name']/a");
foreach($anchors as $a)
{ 
    print $a->nodeValue." - ".$a->getAttribute("href")."<br/>";
}

As per above :) Too slow ..

like image 18
Ryan Avatar answered Nov 14 '22 15:11

Ryan