Append href attribute in hyperlinks with URL in PHP and DOM
I'm using DOM's loadHTMLFile
to grab a page from elsewhere.
I need to find all hyperlinks on the page and then append them so they begin with another, fixed address. E.G.:
Take:
<a href="http://www.google.com"> Google yay! </a>
And turn it into:
<a href="http://cheese.com/http://www.google.com"> Google yay! </a>
Unsure of how to go about doing this. Many thanks in advance for any help. E-Beer for the correct answer.
use $dom->getElementsByTagName('a')
to get a nodeList. Check if the ->length
is greater than 0. If so, iterate with a foreach
or for loop
using the ->length
as the counter and $nodelist->item($i)
. Grab the ->getAttribute('href')
. If it matches a certain pattern using regex testing, then $el->setAttribute($newhref);
精彩评论