【问题标题】:Simple html dom file_get_html not working - is there a more robust way that will handle most cases简单的 html dom file_get_html 不起作用 - 是否有更强大的方法可以处理大多数情况
【发布时间】:2015-02-01 17:45:42
【问题描述】:

我正在使用来自http://simplehtmldom.sourceforge.net 的simple_html_dom.php 来获取维基百科页面上所有图像的完整网址。我主要在寻找公司和组织。下面的脚本适用于少数人,但我收到致命错误:调用非对象上的成员函数 find()... 对于此示例 YouTube 中的许多搜索,以及如果我尝试使用 Facebook 等。我知道这是因为 $html 不是对象。返回网址最成功的方法是什么。请看下面的代码。非常感谢任何帮助。

<html>
<body>
<h2>Search</h2>
<form method="post">
Search: <input type="text" name="q" value="YouTube"/>
<input type="submit" value="Submit">
</form>

<?php

include 'simple_html_dom.php'; 

if (isset($_POST['q'])) 
    {
    $search = $_POST['q'];
    $search = ucwords($search);
    $search = str_replace(' ', '_', $search);  
    $html = file_get_html("http://en.wikipedia.org/wiki/$search");

    ?>
    <h2>Search results for '<?php echo $search; ?>'</h2>
    <ol>
        <?php

        foreach ($html->find('img') as $element): ?>

        <?php $photo = $element->src;

        echo $photo;

        ?>              

        <?php endforeach; 
    ?>
    </ol>
<?php 
}
?>
</body>
</html>

我现在遵循了下面 cmets 中的建议(尽管我可能犯了一个错误),当我点击提交时遇到错误:

警告:DOMDocument::loadHTMLFile(): ID ref_media_type_table_note_2 已在http://en.wikipedia.org/wiki/YouTube 中定义,行:270 in...

警告:DOMDocument::loadHTMLFile(): ID ref_media_type_table_note_2 已在http://en.wikipedia.org/wiki/YouTube 中定义,行:501 in...

请在下面查看我修改后的代码:

<html> 
<body> 
    <form method="post"> Search: 
        <input type="text" name="q" value="YouTube"/> 
        <input type="submit" value="Submit"> </form> 
            <?php 
            if (isset($_POST['q'])) 
                { $search = $_POST['q'];
                  $search = ucwords($search); 
                  $search = str_replace(' ', '_', $search); 
                  $doc = new DOMDocument(); 
                  $doc->loadHTMLFile("http://en.wikipedia.org/wiki/$search"); 

                  foreach ($doc->getElementsByTagName('img') as $image) 
                     echo $image->getAttribute('src'); 

                } 
                ?>
</body> 
</html>

【问题讨论】:

  • 我会避开 SimpleHTMLDom 并坚持使用非常成熟且维护良好的内置 DOM 扩展。 $doc = new DOMDocument(); $doc-&gt;loadHTMLFile("http://en.wikipedia.org/wiki/$search") 应该让你继续前进
  • @phil 非常感谢并为我的无知感到抱歉,但是我将如何实现它来获取 url 图片?
  • foreach ($doc-&gt;getElementsByTagName('img') as $image) echo $image-&gt;getAttribute('src');
  • @phil 抱歉,我肯定犯了错误,因为我不断收到以下代码错误:
    搜索:
    loadHTMLFile("en.wikipedia.org/wiki/$search"); foreach ($doc->getElementsByTagName('img') as $image) echo $image->getAttribute('src'); } ?>
  • 不要在 cmets 中放置大量代码,请编辑您的问题。你遇到了什么错误?

标签: php simple-html-dom


【解决方案1】:
  • 可以安全地忽略这些警告。
  • 您可以在函数前面使用@ 来抑制它们。
  • file_get_html 问题可能可以通过切换到 卷曲。

【讨论】:

    猜你喜欢
    • 2013-09-11
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 2019-01-03
    相关资源
    最近更新 更多