【问题标题】:simple_html_dom example help for a newbie新手的 simple_html_dom 示例帮助
【发布时间】:2025-12-25 12:10:07
【问题描述】:

我正在尝试学习 simple_html_dom 语法,但运气不佳。有人可以给我举个例子吗:

<div id="container">
  <span>Apples</span>
  <span>Oranges</span>
  <span>Bananas</span>
</div>

如果我只想返回值 Apples、Oranges 和 Bananas。

我可以简单地使用 php simple_html_dom 类还是我还必须使用 xcode、curl 等?

更新: 我能够让它工作,但不相信这是获得我需要的最有效的方式:

foreach ($html->find('div[id=cont]') as $div);
foreach($div->find('span') as $element) 
echo $element->innertext . '<br>';

【问题讨论】:

    标签: php screen-scraping simple-html-dom


    【解决方案1】:
    // Create DOM from URL or file
    $html = file_get_html('http://www.google.com/');
    
    // Find all images 
    foreach($html->find('img') as $element) 
           echo $element->src . '<br>';
    
    // Find all links 
    foreach($html->find('a') as $element) 
           echo $element->href . '<br>';
    

    你的建议是正确的:

    foreach ($html->find('div[id=cont]') as $div);
    foreach($div->find('span') as $element) 
    echo $element->innertext . '<br>';
    

    【讨论】:

    • 但是如何将其限制在容器 div 内的项目中?
    【解决方案2】:

    更简单:

    foreach($html->find('div#container span') as $element)
      echo $element->innerText();
    

    这意味着任何从具有 id: 容器的 div 继承的跨度

    【讨论】: