Get text value with PHP simple HTML DOM parser

◇◆丶佛笑我妖孽 提交于 2021-01-28 14:19:16

问题


How can I get the text value where <span>Your name:<span> with the PHP simple HTML DOM parser without children command?

<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>

PHP simple HTML DOM parser api


回答1:


Assuming the HTML in your post is in a variable $str, this is fairly straightforward:

// 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;

If the number of elements changes, you need to check each one for the text you're looking for...

// 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;
    }
}



回答2:


Thank you defines, i try by this and works

$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>";
                        }
                    }


来源:https://stackoverflow.com/questions/33053528/get-text-value-with-php-simple-html-dom-parser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!