提问人:btgen 提问时间:6/3/2022 更新时间:6/3/2022 访问量:38
从 Tag by Atribute 获取内容
get the content from tag by atribute
问:
我需要从名为 的标签名称中获取内容。atribute
a
data-copy
这是我到目前为止得到的非工作代码......
libxml_use_internal_errors(true);
$html=file_get_contents('https://mypage.com/');
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach(
$dom->getElementsByTagName('a') as $thetag){
if($thetag->getAttribute('a')=="data-copy"){echo "<h6>".$thetag->nodeValue."</h6>";}
}
答:
0赞
Markus Zeller
6/3/2022
#1
要检查某个属性是否存在,您需要使用其名称对其进行寻址
$thetag->hasAttribute('data-copy')
要获取数据复制的内容,您可以像这样进行比较
// <a data-copy="valueoftheattribute">
$thetag->getAttribute('data-copy') === 'valueoftheattribute'
0赞
Professor Abronsius
6/3/2022
#2
您还可以使用 an 根据属性的存在或其他更复杂的条件直接查找节点,而无需使用 和 like this:XPath
data-copy
hasAttribute
getAttribute
$file='https://mypage.com/';
libxml_use_internal_errors( true );
$html=file_get_contents( $file );
$dom=new DOMDocument;
$dom->strictErrorChecking=false;
$dom->validateOnParse=false;
$dom->recover=true;
$dom->loadHTML( $html );
libxml_clear_errors();
$xp=new DOMXPath( $dom );
$expr='//a[@data-copy]'; # find `a` nodes anywhere in the source document that simply have the data-copy attribute
# run the query
$col=$xp->query( $expr );
# iterate through any found nodes and display the content
if( $col && $col->length > 0 ){
foreach( $col as $i => $node )printf('<div>[%d] - %s</div>', $i, $node->nodeValue );
}
评论