开发者

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.


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 "\n<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 "\n<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.


You can use

$lines = explode('<br>', $data->nodeValue);


here is a solution in javascript syntax

 var tempArray = $line.split("<br>");  

echo $line[0]
echo $line[1]
echo $line[2]


You can use the php explode function like this. (assuming each line in your <p> tag ends with <br>)

$tags = $dom->getElementsByTagName('blockquote');
foreach($tags as $tag)
{
    $datas = $tag->getElementsByTagName('p');
    foreach($datas as $data)
    {
        $contents = $data->nodeValue;
        $lines = explode('<br>',$contents);
        foreach($lines as $line) {
            echo $line;
        }
    }
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜