在我当前的项目中,我使用xPath解析这个HTML代码:
<div class="prod_view_info">
<p>notimportant</p><p>notimportant</p>
<p>
<b>Putere (Consum/ora): </b> 3W<br>
<b>Fasung: </b> MR16<br>
<b>Tensiune de alimentare: </b> 12V<br>
<b>Flux luminos: </b> 270 - 300 lm<br>
<b>Flux luminos per Watt: </b> 90-100 lm/W<br>
<b>Putere LED: </b> 3* 1W<br>
<b>Frecventa de lucru: </b> DC<br>
<b>Culoarea luminii: </b>alba calda<br>
<b>Temperatura: </b> 30 / 50°C<br>
<b>Material: </b> Aluminiu<br>
<b>Grad de protectie: </b> IP21<br>
<b>Durata de viata: </b> > 50000 ore<br>
<b>Garantie: </b>2 ani<br>
<b>Certificate: </b>
</p>
</div>使用以下PHP代码:
foreach( $xpathprd->query('//div[@class="prod_view_info"]/p[3]/node()') as $techdata ) {
$techdatap = $techdata->nodeValue;
$techdatapChunks = explode(":", trim($techdatap));
$producttechdata[] = $techdatapChunks;
}
$techdata_json = json_encode($producttechdata);
echo "<hr>$techdata_json";重点是获取每一行上的一对信息,并使用json对其进行序列化,例如:
<b>Putere (Consum/ora): </b> 3W<br>应:
["Putere (Consum/ora)","3W"]但是xpath去掉了标记,在某个地方,我遗漏了一些空间,爆炸的结果都搞砸了。
我该怎么做呢?
发布于 2014-09-24 00:23:16
在这种情况下,您可以使用->childNodes和->nextSibling的一些组合,以便更容易地检测。示例:样品演示
$dom = new DOMDocument();
$dom->loadHTML($html_string);
$xpathprd = new DOMXPath($dom);
$data = array();
$elements = $xpathprd->query('//div[@class="prod_view_info"]/p[3]')->item(0);
foreach($elements->childNodes as $child) {
if(isset($child->tagName) && $child->tagName == 'b') { // check if its a `<b>` tag
$key = trim($child->nodeValue);
$value = trim($child->nextSibling->nodeValue); // get the next sibling which is a domtext
$data[] = array($key, $value); // push it inside
}
}
echo '<pre>';
$data = json_encode($data);
print_r($data);应该屈服:
[["Putere (Consum\/ora):","3W"],["Fasung:","MR16"],["Tensiune de alimentare:","12V"],["Flux luminos:","270 - 300 lm"],["Flux luminos per Watt:","90-100 lm\/W"],["Putere LED:","3* 1W"],["Frecventa de lucru:","DC"],["Culoarea luminii:","alba calda"],["Temperatura:","30 \/ 50\u00c2\u00b0C"],["Material:","Aluminiu"],["Grad de protectie:","IP21"],["Durata de viata:","> 50000 ore"],["Garantie:","2 ani"],["Certificate:",""]]https://stackoverflow.com/questions/26006078
复制相似问题