我正在使用domDocument。我很接近,但最后一点需要帮助
我有这个html只是下面的一个片段。有许多行。我正在尝试获取href。
到目前为止,我正在做以下工作:我可以得到表、tr和td,但不确定从那里做什么。
感谢的帮助
foreach ($dom->getElementsByTagName('table') as $tableitem) {
if ( $tableitem->getAttribute('class') == 'tableStyle02'){
$rows = $tableitem->getElementsByTagName('tr');
foreach ($rows as $row){
$cols = $row->getElementsByTagName('td');
$hrefs = $cols->item(0)->getElementsByTagName('a');
}
}
}
html片段:
<table width="100%" border="0" cellspacing="0" cellpadding="2" class="tableStyle02">
<tr>
<td><span class="Name"><a href="bin.php?cid=703&size=0">
<strong>Conference Facility</strong></a></span></td>
<td align="center" nowrap>0.00</td>
<td align="center"> 0 </td>
<td align="center"> </td>
<td align="center"> 0 </td>
<td align="center"> 0 </td>
<td align="center"> 0 - 0 </td>
<td align="center"> Wired Internet, </td>
<td align="center"> </td>
</tr>
让我向您介绍xpath的概念,这是DomDocuments:的一种查询语言
//table[@class="tableStyle02"]//a/@href
读作:取class属性为tableStyle02的table标记,然后取a子标记中的href属性。
或者,正如您对tr
和td
元素的foreach一样:
//table[@class="tableStyle02"]/tr/td/a/@href
现在,在该路径中,a标记是td标记的直接子级,td标记是tr标记的直接子级,tr标记是table标记的直接个子级。正如您所看到的,使用xpath,制定元素的路径要比用PHP代码编写所有内容容易得多。
关于PHP代码,在PHP中,这个可以看起来像:
$doc = new DOMDocument();
$doc->loadHTML($html);
$xp = new DOMXPath($doc);
$href = $xp->evaluate('string(//table[@class="tableStyle02"]//a/@href)');
变量$href
然后包含字符串:bin.php?cid=703&size=0
。
本例使用一个字符串(string(...)
),因此->evaluate
返回一个字符串,该字符串是从第一个找到的属性节点创建的。相反,您也可以返回一个节点列表:
$hrefs = $xp->query('//table[@class="tableStyle02"]/tr/td/span/a/@href');
# ^^^^^ ^^^^
现在$hrefs
包含通常的DOMNodeList
,这里它包含所有href属性节点:
echo $hrefs->item(0)->nodeValue; # bin.php?cid=703&size=0
注意,如果只使用一个斜线/
来分隔标记,则它们必须是直接子级。有两个斜杠//
,它可以是子代(子代或子代(…的子代))。
您应该能够在各个DOMElement实例上使用getAttribute()(就像您在示例的第二行中使用它一样):
foreach ($hrefs as $a_node) {
if ($a_node->hasAttribute('href')) {
print $a_node->getAttribute('href');
}
}
您不必在DOM层次结构中导航即可使用getElementsByTagName
:
foreach ($dom->getElementsByTagName('table') as $tableitem) {
if ($tableitem->getAttribute('class') == 'tableStyle02'){
$links = $tableitem->getElementsByTagName("a");
}
}
此时的$links
现在是DOMNodeList
,因此您可以对其进行迭代:
foreach ($dom->getElementsByTagName('table') as $tableitem) {
if ($tableitem->getAttribute('class') == 'tableStyle02'){
$links = $tableitem->getElementsByTagName("a");
$hrefs = array();
foreach ($links as $link) {
$hrefs[] = $link->getAttribute("href");
}
}
}
// Do things with $hrefs