Ghostff
Ghostff

Reputation: 1458

Use php Get links with attribute from a html file

Here is my HTML

<a href="wateva" title="here she goes">  home </a>
<a href="wateva" title="coming he said"> home </a>
<a href="wateva" title=""> home </a>

And Php

Am trying to get all a tags with attribute "title" but it dosnt work, this is what i have tried.

$html = file_get_contents('home.html');
$dom = new DOMDocument;

@$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');
foreach ($links as $link)
{
   if ($link->getAttribute('name') == "title")
   {
      echo $link->getAttribute('href'). ' ';
      echo $link->nodeValue. '<p>';
   }

}

but it shows a blank Data. how to i fix it, need help

Upvotes: 0

Views: 25

Answers (1)

Marc B
Marc B

Reputation: 360572

getAttribute extracts the value of a named attribute, e.g.:

<a href="foo.html" name="bar">

$node->getAttribute('href'); // returns "foo.html"

You want

$node->hasAttribute('title');

e.g.

<a href="foo.html">             $node->hasAttribute('name') -> false
<a href="foo.html" name="foo">  $node->hasAttribute('name') -> true

Upvotes: 2

Related Questions