PHP DOM解析器在循环时按类获取特定文本 [英] PHP DOM Parser Get Specific text by Class While Looping
本文介绍了PHP DOM解析器在循环时按类获取特定文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究PHP Simple DOM解析器,我想为我的问题提供一个简单的解决方案
I am working on a PHP Simple DOM Parser and i want a simple solution for my question
<tr>
<td class="one">1</td>
<td class="two">2</td>
<td class="three">3</td>
</tr>
<tr>
<td class="one">10</td>
<td class="two">20</td>
<td class="three">30</td>
</tr>...
我的html与上面的类似
the html of mine is will look similar to the above
我正在遍历 td 这样的
foreach ($sample->find("td") as $ele)
{
if($ele->class == "one")
echo "ONE = ".$ele->plaintext;
if($ele->class == "two")
echo "TWO= ".$ele->plaintext;
}
但是有没有一种简单的解决方案,如果条件没有得到特定类的明文,我也不需要速记我期待下面这样的事情
But is there any simple solution that without if condition getting the plaintext of particular class i dont want shorthand if also I am expecting something like this below
$ele->class->one
推荐答案
看看:
<?php
$html = "
<table>
<tr>
<td class='one'>1</td>
<td class='two'>2</td>
<td class='three'>3</td>
</tr>
<tr>
<td class='one'>10</td>
<td class='two'>20</td>
<td class='three'>30</td>
</tr>
</table>
";
// Your class name
$classeName = 'one';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
// Get the results
$results = $xpath->query("//*[@class='" . $classeName . "']");
for($i=0; $i < $results->length; $i++) {
echo $review = $results->item($i)->nodeValue . "<br>";
}
?>
这篇关于PHP DOM解析器在循环时按类获取特定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文