Domxpath find element with exact name

Asked

Viewed 89 times

1

I’m having a problem trying to find an element with the exact name.

<?
//...
@$DOM = new DOMDocument;
@$DOM->loadHTML($html);
@$finder = new DomXPath($DOM); 

foreach($finder->query("//a[contains(@title, '".$info[$i]."')]") as $link){
            echo $l[$i] = $link->getAttribute('href').'<br>';
}
//...    
?>

Your answer is several links (taken from getAtrribute()), hassle-free.

Where is the problem?

I wish I could take just what title was the same as $info[$i].

Exemplifying (note the title!):

<a href='1.html' title="biscoito"></a>
<a href='2.html' title="biscoito bolacha"></a>
<a href='3.html' title="bolacha"></a>

If the $info[$i] had the value of "biscoito", would be returned:

1.html //oriundo do biscoito
2.html //oriundo do biscoito bolacha

Desired result:

1.html

Solution I need:

There be some function (which I don’t know) that only contains the name, but not only the name. Because I need only where the title is equal to cookie, but not the cookie.

1 answer

0


I was able to find a solution to the problem.

Solution:

<?
//...
@$DOM = new DOMDocument;
@$DOM->loadHTML($html);
@$finder = new DomXPath($DOM); 

foreach($finder->query("//a[@title='".$info[$i]."']") as $link){
            echo $l[$i] = $link->getAttribute('href').'<br>';
}
//...    
?>

In short:

Replace "//a[contains(@title, 'biscoito')]" for "//a[@title='biscoito']".

Explanation:

The = will only display what is equal, instead of just containing the string. Just what I was looking for.

Note:

There is another function that is starts-with (becoming: //a[starts-with(@title,"biscoito")]), in this case would not help at all, but if you have the same problem you can test it. In case of search for cookie, would only display one, instead of two, for example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.