我想使用php和简单的HTML解析器来分析页面。
HTML标记如下:
<div class="question">
<b>My-title1</b><br />
<label class="false"><input type="radio" name="q1" value="0" />1. <span >text-1</span></label><br />
<label class="true"><input type="radio" name="q1" value="1" />2. <span >text-2</span></label><br />
<label class="false"><input type="radio" name="q1" value="0" />3. <span >text-3</span></label><br />
<label class="false"><input type="radio" name="q1" value="0" />4. <span >text-4</span></label><br />
</div>现在,我使用这段代码获取My-title值:
foreach($html->find('b') as $e)
{
echo $e->innertext . '<br>';
}但我想要更多..。
我想把text-1转到text-4,并找到并过滤其中的哪一个有class=true
因此,我的最后输出必须是:
my-title1
text-1
*text-2
text-3
text-4
my-title2
text-1
text-2
text-3
*text-4
...我怎么能用这个?这是我的方式,还是我必须使用另一种解决方案来做到这一点?
发布于 2014-07-04 01:02:46
是的,您绝对需要使用另一个解决方案来获得值。首先,由于您需要另一组包含title和text的值,因此需要扩展搜索范围,即针对父元素<div class="question">。
这一定是你的出发点。从那里开始,很明显你需要循环然后处理孩子们。考虑一下这个例子:
include 'simple_html_dom.php';
// sample markup
$markup = '
<div class="question">
<b>My-title1</b><br />
<label class="false"><input type="radio" name="q1" value="0" />1. <span>text-1</span></label><br />
<label class="true"><input type="radio" name="q1" value="1" />2. <span>text-2</span></label><br />
<label class="false"><input type="radio" name="q1" value="0" />3. <span>text-3</span></label><br />
<label class="false"><input type="radio" name="q1" value="0" />4. <span>text-4</span></label><br />
</div>
<div class="question">
<b>My-title2</b><br />
<label class="false"><input type="radio" name="q1" value="0" />1. <span>text-1</span></label><br />
<label class="false"><input type="radio" name="q1" value="1" />2. <span>text-2</span></label><br />
<label class="false"><input type="radio" name="q1" value="0" />3. <span>text-3</span></label><br />
<label class="true"><input type="radio" name="q1" value="0" />4. <span>text-4</span></label><br />
</div>
';
$html = str_get_html($markup);
// get each `question class` parent
foreach($html->find('div[class="question"]') as $question_tag) {
// get the title
$title = $question_tag->children(0)->innertext; // title tag child
echo $title . '<br/>';
// texts inside span
foreach($question_tag->find('label input span') as $span) {
if($span->parent()->class == 'true') {
echo '*';
}
echo $span->innertext . '<br/>';
}
}应该产生这样的结果:
My-title1
text-1
*text-2
text-3
text-4
My-title2
text-1
text-2
text-3
*text-4https://stackoverflow.com/questions/24563407
复制相似问题