【问题标题】:Get attribute based on simple HTML DOM基于简单的 HTML DOM 获取属性
【发布时间】:2012-04-06 10:57:00
【问题描述】:

如何获取 HTML 页面上 href 属性的内容,基于simple HTML DOM。 这是我的脚本示例:

<?php
/* update your path accordingly */
include_once 'simple_html_dom.php';

$url = "http://www.codesphp.com/";
$html = file_get_html($url);
$ret =  $html->find('span.titleSnnipets');



foreach($ret as $story){
    echo $story->find('a',0).'<br/>';
}
?>

此脚本检索页面上的所有标签,我尝试检索所有链接的属性内容。

【问题讨论】:

  • 这是什么,我什至不...
  • 由于我们无法访问您的本地主机,我们无法看到内容。这很难帮你解决。

标签: php html url dom href


【解决方案1】:

按照我的理解,你想要获取包含在类“titleSnnipets”的“span”中的每个链接的“href”,如果是这样,你可以这样做

<?php
/* update your path accordingly */
include_once 'simple_html_dom.php';

$url = "http://www.codesphp.com/";
$html = file_get_html($url);
$ret =  $html->find('span.titleSnnipets');

foreach($ret as $elements) {
    foreach($elements->find('a') as $link) {
        echo $link->href . '<br>';
    }
}
?>

【讨论】:

    【解决方案2】:

    由于我们无法看到您本地主机的内容,因此很难为您提供帮助。我只看到了一件我知道可以优化的小事,那就是第一次 find() 调用。

    <?php
    include_once 'simple_html_dom.php';
    
    $url = "http://localhost/website/";
    $html = file_get_html($url);
    $ret =  $html->find('span.title');
    
    foreach($ret as $story)
    {
        echo $story->find('a',0).'<br/>';
    }
    ?>
    

    更新: 我已经说过,由于我看不到您正在使用的内容,因此很难为您提供帮助。您的回应是再次寻求帮助,但不努力提供内容?由于您拒绝让您的内容可访问,我已重写您的代码以使用 google 代替。此示例按预期工作。接受并根据需要进行修改。在您提供内容之前,我无法为您提供更多帮助。

    <?php
    include_once 'simple_html_dom.php';
    $html = file_get_html('http://www.google.com/');
    $divs = $html->find('div.gbm');
    foreach($divs as $element)
    {
        echo $element->find('a', 0).'<br>';
    }
    ?>
    

    更新 #2:这将拉取页面上的所有链接并显示它们。

    <?php
    include_once 'simple_html_dom.php';
    $html = file_get_html('http://www.codesphp.com/');
    $links = $html->find('a');
    foreach($links as $link)
    {
        echo $link->href.'<br>';
    }
    ?>
    

    【讨论】:

    • 我纠正了代码很好,那么我的问题的解决方案是什么
    • 我已经更正了第一个帖子,我把链接放到我的网站codesphp.com,但是我想检索所有链接的 href 属性的内容。
    • 不客气。如果我的回答和 cmets 对你有帮助,请考虑给他们点赞。
    猜你喜欢
    • 1970-01-01
    • 2015-08-27
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    相关资源
    最近更新 更多