Php 如何从html页面获取文本链接?

Php 如何从html页面获取文本链接?,php,html,file-get-contents,Php,Html,File Get Contents,我想从这个网页上获取链接“&”。我想要 使用DOM解析器来实现这一点: $dom = new DOMDocument; $dom->loadHTML($html); // $html is a string containing the HTML foreach ($dom->getElementsByTagName('a') as $link) { echo $link->getAttribute('href').'<br/>'; } 更新:如果您

我想从这个网页上获取链接“&”。我想要

使用DOM解析器来实现这一点:

$dom = new DOMDocument;
$dom->loadHTML($html); // $html is a string containing the HTML

foreach ($dom->getElementsByTagName('a') as $link) {
    echo $link->getAttribute('href').'<br/>';
}


更新:如果您只需要特定
中的链接,可以使用表达式查找div中的链接,然后循环它们以获得
href
属性:

$dom = new DOMDocument;
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$links_inside_div = $xpath->query("//*[contains(@class, 'link')]/a");

foreach ($links_inside_div as $link) {
    echo $link->getAttribute('href').'<br/>';
}
$dom=新的DOMDocument;
$dom->loadHTML($html);
$xpath=newdomxpath($dom);
$links\u inside\u div=$xpath->query(“/*[contains(@class,'link')]]/a”);
foreach($links\u inside\u div as$link){
echo$link->getAttribute('href')。
; }

您可以使用snoopy PHP类。Snoopy是一个模拟web浏览器的PHP类。它自动化了检索网页内容和发布表单的任务

否则,请尝试使用Jquery

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
 <script type="text/javascript">
    $( document ).ready(function() {
         $( ".link a" ).each(function( index ) {
             var link = $( this ).attr("href") );
             alert(link );
         });
    });
</script>

选中此项,我只想获得这些标签内的链接注意:还有许多其他标签是there@SarathMohan:更新了我的答案
警告:DOMDocument::loadHTML():HTMLParserEntityRef:应为“;”在实体中,第7行的C:\xampp\htdocs\fetch\bkadafetch.php中的第38行
这是我执行代码时的输出,第7行包含
$dom->loadHTML($html)虽然这被认为不是一个很好的实践,但是您可以使用
@$dom->loadHTML($html)以抑制警告。更好的方法可能是使用
libxml\u internal\u errors()
。看见
http://www.w3schools.com/default.asp
http://www.google.com
$dom = new DOMDocument;
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$links_inside_div = $xpath->query("//*[contains(@class, 'link')]/a");

foreach ($links_inside_div as $link) {
    echo $link->getAttribute('href').'<br/>';
}
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
 <script type="text/javascript">
    $( document ).ready(function() {
         $( ".link a" ).each(function( index ) {
             var link = $( this ).attr("href") );
             alert(link );
         });
    });
</script>
 var list = document.getElementsByTagName("a");