我正在尝试从我的网站中提取一些数据。这很简单,但是我找不到任何好的示例/文档,因此我很难过。我正在尝试为我的朋友们创建一个API来使用我的博客,但这有点困难。假设我有一个网站http://www.sample.com,并且该网站的html源是:
<div class="container">
<a href="/mywebsiteblogpost/">
<h2 class="title">im the best</h2>
</a>
<span class="author">Josue Espinosa</span>
<div class="thumb"> <img src="http://www.sample.com/imgsrc" alt="">
<span class="category">sports</span>
</div>
<p>preview text</p>
<a class="more" href="/mywebsiteblogpost/">full text...</a>
</div>
我希望能得到大家.container
的孩子,第一个a
孩子的href
价值,之类的文本值title
,author
中,img src
为孩子里面.thumb
,和文本价值category
。
我从开始a href src
,但还没走那么远。我以为$ title会在容器内回显第一个锚标记的href值,但它不起作用。
$text = file_get_contents('http://www.sample.com');
$doc = new DOMDocument('1.0');
$doc->loadHTML($text);
foreach($doc->getElementsByTagName('div') AS $div) {
$class = $div->getAttribute('class');
if(strpos($class, 'container') !== FALSE) {
// title doesnt retrieve the href value of title :(
$title = 'TITLE'.$div->getElementsByTagName('a')->getAttribute('href').'<br>';
//this echos all the text in all of the children of $div
echo $div->textContent.'<br>';
}
}
谁能解释为什么?
罪魁祸首是$div->getElementsByTagName('a')->getAttribute('href')
。第一部分,$div->getElementsByTagName('a')
检索元素列表,而不是单个元素。因此,以下操作->getAttribute('href')
不会正确。
要解决此问题,请像使用div
-tags一样进行迭代:
foreach($div->getElementsByTagName('a') as $a) {
$href = $a->getAttribute('href');
if ($href) echo "TITLE$href<br>";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句