note 100228 added to domdocument.getelementsbytagname
| From: | calvinatgmail at osu1 dot php dot net | Date: | Sat, 02 Oct 2010 23:41:07 +0000 |
| Subject: | note 100228 added to domdocument.getelementsbytagname | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-172899@lists.php.net to get a copy of this message | ||
My first post!
And this is how I get elements by attribute and its value.
For an example, if I want to grab all DIV tags with class name 'className', then...
<?php
$some_link = 'some website';
$tagName = 'div';
$attrName = 'class';
$attrValue = 'className';
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
@$dom->loadHTMLFile($some_link);
$html = getTags( $dom, $tagName, $attrName, $attrValue );
echo $html;
function getTags( $dom, $tagName, $attrName, $attrValue ){
$html = '';
$domxpath = new DOMXPath($dom);
$newDom = new DOMDocument;
$newDom->formatOutput = true;
$filtered = $domxpath->query("//$tagName" . '[@' . $attrName .
"='$attrValue']");
// $filtered = $domxpath->query('//div[@class="className"]');
// '//' when you don't know 'absolute' path
// since above returns DomNodeList Object
// I use following routine to convert it to string(html); copied it from someone's post in
this site. Thank you.
$i = 0;
while( $myItem = $filtered->item($i++) ){
$node = $newDom->importNode( $myItem, true ); // import node
$newDom->appendChild($node); // append node
}
$html = $newDom->saveHTML();
return $html;
}
?>
Please, improve it, and share it.
----
Server IP: 69.147.83.197
Probable Submitter: 68.161.233.74
----
Manual Page -- http://www.php.net/manual/en/domdocument.getelementsbytagname.php
Edit -- https://master.php.net/note/edit/100228
Del: integrated -- https://master.php.net/note/delete/100228/integrated
Del: useless -- https://master.php.net/note/delete/100228/useless
Del: bad code -- https://master.php.net/note/delete/100228/bad+code
Del: spam -- https://master.php.net/note/delete/100228/spam
Del: non-english -- https://master.php.net/note/delete/100228/non-english
Del: in docs -- https://master.php.net/note/delete/100228/in+docs
Del: other reasons-- https://master.php.net/note/delete/100228
Reject -- https://master.php.net/note/reject/100228
Search -- https://master.php.net/manage/user-notes.php