我正在使用simplehtmldom来解析html而我只是解析位于任何标记之外的明文(但是在两个不同的标记之间):
<div class="text_small">
<b>?dress:</b> 7 Hange Road<br>
<b>Phone:</b> 415641587484<br>
<b>Contact:</b> Alex<br>
<b>Meeting Time:</b> 12:00-13:00<br>
</div>
Run Code Online (Sandbox Code Playgroud)
是否有可能获得地址,电话,联系人,会议时间的这些价值?我想知道是否有机会将CSS选择器传递给nextSibling/previousSibling函数...
foreach($html->find('div.text_small') as $div_descr)
{
foreach($div_descr->find('b') as $b)
{
if ($b->innertext=="?dress:") {//someaction
}
if ($b->innertext=="Phone:") { //someaction
}
if ($b->innertext=="Contact:") { //someaction
}
if ($b->innertext=="Meeting Time:") { //someaction
}
}
}
Run Code Online (Sandbox Code Playgroud)
我应该用什么而不是"某种行为"?
UPD.是的,我没有编辑目标页面的权限.否则,它值得吗?:)
可能有一个更简单的解决方案。(也许使用 simple_html_dom 之外的其他东西)
我还没有找到合适的选择器,并且 nextSibling() 只返回下一个同级元素。(这有点奇怪。simple_html_dom_node存储两个数组,$children和$nodes。Textnodes在$nodes中,但不在$children中。next_sibling()对$children进行操作)。
但由于 $nodes 是 simple_html_dom_node 的公共属性,您自己编写一些迭代器。
<?php
require_once 'simplehtmldom/simple_html_dom.php';
$html = str_get_html('<html><head><title>...</title></head><body>
<div class="text_small">
<b>Adress:</b> 9 Hange Road<br>
<b>Phone:</b> 999641587484<br>
<b>Contact:</b> Alex<br>
<b>Meeting Time:</b> 12:00-13:00<br>
</div>
<div class="text_small">
<b>Adress:</b> 8 Hange Road<br>
<b>Phone:</b> 888641587484<br>
<b>Contact:</b> Bob<br>
<b>Meeting Time:</b> 13:00-14:00<br>
</div>
</body></html>');
foreach($html->find('div.text_small') as $div) {
$result = parseEntry($div);
foreach($result as $r) {
echo "'$r[name]' - '$r[text]'\n";
}
echo "========\n";
}
function parseEntry(simple_html_dom_node $div) {
$result = array();
$current = null;
for($i=0; $i<count($div->nodes); $i++) {
if ( HDOM_TYPE_ELEMENT===$div->nodes[$i]->nodetype) {
if ( !is_null($current) ) {
$result[] = $current;
$current = null;
}
if ('b'===$div->nodes[$i]->tag) {
$current = array('name'=>$div->nodes[$i]->text(), 'text'=>'');
}
}
else if (HDOM_TYPE_TEXT===$div->nodes[$i]->nodetype && !is_null($current)) {
$current['text'] .= $div->nodes[$i]->text();
}
}
if ( !is_null($current) ) {
$result[] = $current;
}
return $result;
}
Run Code Online (Sandbox Code Playgroud)
印刷
'Adress:' - ' 9 Hange Road'
'Phone:' - ' 999641587484'
'Contact:' - ' Alex'
'Meeting Time:' - ' 12:00-13:00'
========
'Adress:' - ' 8 Hange Road'
'Phone:' - ' 888641587484'
'Contact:' - ' Bob'
'Meeting Time:' - ' 13:00-14:00'
========
Run Code Online (Sandbox Code Playgroud)
在其他人找到更简单的解决方案之前,您可能希望以此为起点。