我建立个人使用的基本画面刮刀和学习的目的,所以请不要发布类似“你要问权限”等访问孩子的div使用DOM文档和XPath
我的数据评论试图访问结构如下:
<tr>
<td>
<div class="wrapper">
<div class="randomDiv">
<div class="divContent">
<div class="event">asd</div>
<div class="date">asd</div>
<div class="venue">asd</div>
<div class="state">asd</div>
</div>
</div>
</div>
</td>
</tr>
我试图收集所有这些数据(因为有大约20行在给定的页面上)。
使用下面的代码我已成功地收集数据,我需要:
$remote = file_get_contents("linktoURL");
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$file = @$doc->loadHTML($remote);
$rows = $doc->getElementsByTagName('tr');
$xp = new DOMXpath($doc);
//initialize variables
$rows = array();
foreach($xp->query('//*[contains(@class, \'wrapper\')]', $doc) as $found) {
echo "<pre>";
print_r($found->nodeValue);
}
现在的问题是,我将如何去存储所有这些数据转化为关联数组象下面这样:
Array (
[0] => Array
(
[Event] => Name
[Date] => 12/12/12
[Venue] => NameOfPlace
[state] => state
)
[1] => Array
(
[Event] => Name
[Date] => 12/12/12
[Venue] => NameOfPlace
[state] => state
)
[2] => Array
(
[Event] => Name
[Date] => 12/12/12
[Venue] => NameOfPlace
[state] => state
)
)
现在,唯一想到的解决方案是在foreach循环中为每个类名称//*[contains(@class, \'className\')]
调用xpath查询。
通过DOMDocument和XPath有没有更习惯的方式,其中我能够创建上述数据的关联数组?
编辑:
我不限于使用DOM文档和XPath,如果有其他的解决方案,这可能是更容易的话,请张贴。
有库,它允许您选择使用CSS样式选择节点缩短您的XPath的使用。我现在不记得它的名字了。 – alex 2010-09-26 12:48:14