gpt4 book ai didi

php - DomDocument 解析换行符适用于 span 但不适用于 img

转载 作者:数据小太阳 更新时间:2023-10-29 02:34:04 24 4
gpt4 key购买 nike

参见此处:https://ideone.com/bjs3IC

为什么使用 span 而不是 img 可以正确显示换行符?

<?php
outputImages();
outputSpans();




function outputImages(){
$html = "<div class='test'>
<pre>
<img src='http://d...content-available-to-author-only...e.com/5x5/000/fff'>
<img src='http://d...content-available-to-author-only...e.com/5x5/000/fff'>
<img src='http://d...content-available-to-author-only...e.com/5x5/000/fff'>
</pre>
</div>";
getHtml($html);
}


function outputSpans(){
$html = "<div class='test'>
<pre>
<span>a</span>
<span>b</span>
<span>c</span>
</pre>
</div>";
getHtml($html);
}


function getHtml($html){
$doc = new DOMDocument;
$doc->loadhtml($html);
$xpath = new DOMXPath($doc);
$tags = $xpath->query('//div[@class="test"]');
print(get_inner_html($tags[0]));
}


function get_inner_html( $node ) {
$innerHTML= '';
$children = $node->childNodes;
foreach ($children as $child) {
$innerHTML .= $child->ownerDocument->saveXML( $child );
}

return $innerHTML;
}

最佳答案

DOMDocument::loadHTML 函数有第二个options 参数。看起来 LIBXML_NOBLANKS 是(至少其中之一)那里的默认值。

你可以使用

$doc->loadhtml($html, LIBXML_NOEMPTYTAG);

要覆盖该默认值,您的代码将对这两个示例起到相同的作用。

附注
不确定为什么要使用

print(get_inner_html($tags[0]));

$tags 变量是一个DOMNodeList,因此您应该使用$tags->item(0) 来获取第一个标签。

您的完整代码应如下所示:

outputImages();
outputSpans();

function outputImages() {
$html = "<div class='test'>
<pre>
<img src='http://d...content-available-to-author-only...e.com/5x5/000/fff'>
<img src='http://d...content-available-to-author-only...e.com/5x5/000/fff'>
<img src='http://d...content-available-to-author-only...e.com/5x5/000/fff'>
</pre>
</div>";
getHtml($html);
}

function outputSpans() {
$html = "<div class='test'>
<pre>
<span>a</span>
<span>b</span>
<span>c</span>
</pre>
</div>";
getHtml($html);
}

function getHtml($html) {
$doc = new DOMDocument;
$doc->loadHTML($html, LIBXML_NOEMPTYTAG);
$xpath = new DOMXPath($doc);
$tags = $xpath->query('//div[@class="test"]');
print(get_inner_html($tags->item(0)));
}

function get_inner_html( $node ) {
$innerHTML= '';
$children = $node->childNodes;
foreach ($children as $child) {
$innerHTML .= $child->ownerDocument->saveXML( $child );
}
return $innerHTML;
}

关于php - DomDocument 解析换行符适用于 span 但不适用于 img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37312597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com