简单的html dom file_get_html不起作用 - 是否有一种更强大的方法来处理大多数情况


Simple html dom file_get_html not working - is there a more robust way that will handle most cases

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

<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>

我现在遵循了下面评论中的建议(尽管我可能犯了一个错误(,并且在单击提交时遇到错误:

警告: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>
  • 这些警告可以安全地忽略。
  • 您可以使用函数前面的@来抑制它们。
  • file_get_html问题可能可以通过切换到卷曲。
相关文章: