I have searched a lot for this but have not yet found anything that works...
I would like to find all the anchor tags in another php file and echo their names (with an href to their location in the document).
For example, I have this in one file:
<a name="test"></a>
and would like to find all of them using some code in my main php file and print them all...
Here's what I've tried:
$dom = new DOMDocument;
$dom->loadHTML($content);
foreach( $dom->getElementsByTagName('a') as $node ) {
echo $node->getAttribute( 'name' );
}
I know it's not exactly super specific but yeah, thanks.
EDIT: How about a way to find and echo anchors on the current page?
look here for the actual site: http://robertwbooth.co.uk
You can try
$html = file_get_html("http://xxxxxx/support/content-entry/create-anchor-tags/");
$anchor = array();
foreach ( $html->find("a") as $link ) {
if ($link->href === false) {
$key = $link->id ? $link->id : ($link->name ? $link->name : false);
if (! $key)
continue;
if (isset($anchor[$link->id])) {
$anchor[$link->id] = array_merge($anchor[$link->id], array("name" => $link->name,"id" => $link->id));
} else {
$anchor[$link->id] = array("name" => $link->name,"id" => $link->id);
}
} else {
if (strpos($link->href, "#") === 0) {
if (isset($anchor[substr($link->href, 1)])) {
$anchor[substr($link->href, 1)] = array_merge($anchor[substr($link->href, 1)], array("text" => $link->plaintext));
} else {
$anchor[substr($link->href, 1)] = array("text" => $link->plaintext);
}
}
}
}
var_dump($anchor);
Output
array
'id507d815fd9383' =>
array
'name' => string 'id507d815fd9383' (length=15)
'id' => string 'id507d815fd9383' (length=15)
'text' => string 'Visit the Useful Tips Section' (length=29)
'id507d815fd93a3' =>
array
'name' => string 'id507d815fd93a3' (length=15)
'id' => string 'id507d815fd93a3' (length=15)
'text' => string 'Visit the Useful Tips Section' (length=29)
'id507d815fd93bc' =>
array
'name' => string 'id507d815fd93bc' (length=15)
'id' => string 'id507d815fd93bc' (length=15)
'text' => string 'Visit the Useful Tips Section' (length=29)
'id507d815fd93d3' =>
array
'name' => string 'id507d815fd93d3' (length=15)
'id' => string 'id507d815fd93d3' (length=15)
'text' => string 'Visit the Useful Tips Section' (length=29)
'id507d815fd93eb' =>
array
'name' => string 'id507d815fd93eb' (length=15)
'id' => string 'id507d815fd93eb' (length=15)
'text' => string 'Visit the Useful Tips Section' (length=29)
'id507d815fd9404' =>
array
.......... so many more