使用 PHP 简单 HTML DOM 解析器获取文本值
Get text value with PHP simple HTML DOM parser
如何使用没有子命令的 PHP 简单 HTML DOM 解析器获取 <span>Your name:<span>
处的文本值?
<div class="adds-info">
<span>price:<span>1000000000 </span></span>
<span>txt1</span>
<span>Your name:<span>aaa</span></span>
<span>Phone:<span>02632402210</span></span>
</div>
假设 post 中的 HTML 在变量 $str
中,这很简单:
// Parse the HTML string into a DOM object
$html = str_get_html($str);
// Find the second nested span inside the <div class="adds-info">, then get its parent
$span = $html->find('.adds-info span span', 1)->parent;
// Get the innerhtml of the parent span
$name = $span->innertext;
如果元素的数量发生变化,您需要检查每个元素是否包含您要查找的文本...
// Get all spans inside the <div class="adds-info">
$spans = $html->find('.adds-info span');
// Loop through each span, looking for "Your name:"
foreach ($spans as $span) {
if (strpos($span->innerhtml, "Your name:") !== FALSE) {
$name = $span->innerhtml;
}
}
谢谢你的定义,我试了一下,成功了
$spans = '.adds-info span';
foreach($spans as $n){
if (strpos($n->innertext, "Your name:") !== FALSE) {
$name = $n->innertext;
$name = str_replace('Your name:', '', $name);
echo "Name: " . $name . "<hr>";
}
}
如何使用没有子命令的 PHP 简单 HTML DOM 解析器获取 <span>Your name:<span>
处的文本值?
<div class="adds-info">
<span>price:<span>1000000000 </span></span>
<span>txt1</span>
<span>Your name:<span>aaa</span></span>
<span>Phone:<span>02632402210</span></span>
</div>
假设 post 中的 HTML 在变量 $str
中,这很简单:
// Parse the HTML string into a DOM object
$html = str_get_html($str);
// Find the second nested span inside the <div class="adds-info">, then get its parent
$span = $html->find('.adds-info span span', 1)->parent;
// Get the innerhtml of the parent span
$name = $span->innertext;
如果元素的数量发生变化,您需要检查每个元素是否包含您要查找的文本...
// Get all spans inside the <div class="adds-info">
$spans = $html->find('.adds-info span');
// Loop through each span, looking for "Your name:"
foreach ($spans as $span) {
if (strpos($span->innerhtml, "Your name:") !== FALSE) {
$name = $span->innerhtml;
}
}
谢谢你的定义,我试了一下,成功了
$spans = '.adds-info span';
foreach($spans as $n){
if (strpos($n->innertext, "Your name:") !== FALSE) {
$name = $n->innertext;
$name = str_replace('Your name:', '', $name);
echo "Name: " . $name . "<hr>";
}
}