Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

php - DOMDocument : how to get inner HTML as Strings separated by line-breaks?

<blockquote>
 <p>
   2 1/2 cups sweet cherries, pitted<br>
   1 tablespoon cornstarch <br>
   1/4 cup fine-grain natural cane sugar
 </p>
</blockquote>

hi , i want to get the text inside 'p' tag . you see there are three different line and i want to print them separately after adding some extra text with each line . here is my code block

    $tags = $dom->getElementsByTagName('blockquote');
    foreach($tags as $tag)
    {
        $datas = $tag->getElementsByTagName('p');
        foreach($datas as $data)
        {
            $line = $data->nodeValue;
            echo $line;
        }
    } 

main problem is $line contains the full text inside 'p' tag including 'br' tag . how can i separate the three lines to treat them respectively ??

thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do that with XPath. All you have to do is query the text nodes. No need to explode or something like that:

$dom = new DOMDocument;
$dom->loadHtml($html);
$xp = new DOMXPath($dom);
foreach ($xp->query('/html/body/blockquote/p/text()') as $textNode) {
    echo "
<li>", trim($textNode->textContent);
}

The non-XPath alternative would be to iterate the children of the P tag and only output them when they are DOMText nodes:

$dom = new DOMDocument;
$dom->loadHtml($html);
foreach ($dom->getElementsByTagName('p')->item(0)->childNodes as $pChild) {
    if ($pChild->nodeType === XML_TEXT_NODE) {
        echo "
<li>", trim($pChild->textContent);
    }
}

Both will output (demo)

<li>2 1/2 cups sweet cherries, pitted
<li>1 tablespoon cornstarch
<li>1/4 cup fine-grain natural cane sugar

Also see DOMDocument in php for an explanation of the node concept. It's crucial to understand when working with DOM.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...