使用php获取当前文档中div的内容

时间:2014-09-25 09:47:16

标签: php html

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

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

2 个答案:

答案 0 :(得分: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];

?>

答案 1 :(得分:-1)

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

我认为这会奏效。