Van Tho
Van Tho

Reputation: 633

How to get link inside tag a html (html as plain text) in PHP?

I have the following code

$input = '<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<a class="class1 class2" href="link-to-web1.html">Link</a>
<a class="class1 class2" href="abc/link-to-web1.html">Link</a>
<a class="class1 class2" href="abc/xyz/link-to-web1.html">Link</a>

<a class="another" href="abc/xyz/link.html">Link</a>
</body>
</html>';

I got this string after using curl. Then I wanna get all link (href link) of all a tag with class 'class1 class2', how to do that? I had tried some method but it's not work :(

Upvotes: 0

Views: 424

Answers (1)

Ravinder Reddy
Ravinder Reddy

Reputation: 3879

Use the DOMDocument

$dom = new DOMDocument;
// load your html
$dom->loadHTML($input);
// loop all the anchor tags 
foreach ($dom->getElementsByTagName('a') as $a) {
     // check the calss
     if($a->getattribute('class') == 'class1 class2') {
          // echo href 
          echo $a->getattribute('href')."<br/>";
     }
}

Out put:

link-to-web1.html
abc/link-to-web1.html
abc/xyz/link-to-web1.html

Upvotes: 1

Related Questions