【问题标题】:Get content of a div in the current document with php用php获取当前文档中某个div的内容
【发布时间】:2023-03-22 08:09:01
【问题描述】:

我想用php获取'count-link'的内容(只有数字):

<div class="left">
<a class="count-link" href="http://url.com">
<span>22</span>
users
</a>
</div>

我试过了,但是没用:

$doc = new DomDocument();
$div = $doc->getElementByClass('count-link');
if($div) {
echo $div->textContent;
}

【问题讨论】:

标签: php html


【解决方案1】:

这将工作(测试):

<?php

function getTextBetweenTags($tag, $html, $strict=0)
{
    /*** a new dom object ***/
    $dom = new domDocument;

    /*** load the html into the object ***/
    if($strict==1)
    {
        $dom->loadXML($html);
    }
    else
    {
        $dom->loadHTML($html);
    }

    /*** discard white space ***/
    $dom->preserveWhiteSpace = false;

    /*** the tag by its tag name ***/
    $content = $dom->getElementsByTagname($tag);

    /*** the array to return ***/
    $out = array();
    foreach ($content as $item)
    {
        /*** add node value to the out array ***/
        $out[] = $item->nodeValue;
    }
    /*** return the results ***/
    return $out;
}

$html = '<div class="left">
<a class="count-link" href="http://url.com">
<span>22</span>
users
</a>
</div>';

//Example output array
print_r(getTextBetweenTags("span", $html));

//Example save in array
$myArr = getTextBetweenTags("span", $html);

//Example print text only
echo $myArr[0];

//Example save text only to var
$myText = $myArr[0];

?>

【讨论】:

  • 我必须在此处为标记名插入什么? “跨度” ?如果我想要当前文件,我应该为 $html 插入什么?
  • 我不明白你的意思?标签名称显然是“span”。但是你对当前文件是什么意思?是否要处理尚未输出的html?在那种情况下,使用正则表达式不是更容易吗?编辑:如果您向下滚动代码,有一个示例使用。
  • 在代码中添加了示例。向下滚动,您应该会找到您可能需要的一切。
【解决方案2】:
<div class="left">
<a class="count-link" href="http://url.com">
<span id= "span_value">22</span>
users
</a>
</div>

$doc = new DomDocument();
$div = $doc->getElementById('span_value');
if($div) {
echo $div->textContent;
}

我认为这会奏效。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
相关资源
最近更新 更多