simple_html_dom帮助新手

时间:2012-11-21 20:24:52

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

我正在尝试学习simple_html_dom语法,但我没有太多运气。有人可以告诉我一个例子:

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

如果我想返回苹果,橘子和香蕉的价值。

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

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

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

2 个答案:

答案 0 :(得分:2)

// 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>';

答案 1 :(得分:1)

更简单:

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

这意味着任何从具有id:container

的div下降的跨度
相关问题