簡體   English   中英

如何獲取標簽內容?

[英]How to get tag content?

我正在制作一個腳本來獲取其他頁面內容,現在我正在開發一個應該獲得標簽內容的功能......但我有點卡住:D

found a new tag of same kind inside tag...
nothing found...
1111
2222

打印出來。

<?php

function d($toprint)
{
    echo $toprint."<br />";
}

function GetTagContents($source, $tag, $pos)
{   
    $startTagPos        = strpos( $source, "<".$tag, $pos );
    $startTagEndPos     = strpos( $source, ">", $startTagPos )+1;

    $endTagPos          = strpos( $source, "</".$tag, $startTagEndPos);

    $lastpos = $startTagPos+1;    
    while( $lastpos != False )
    {
        $newStartTagPos = strpos( $source, "<".$tag, $lastpos );

        if( $newStartTagPos == False )
        {
            d("nothing found...");
            $lastpos = False;        
        }
        else if( $newStartTagPos > $endTagPos )
        {
            d("out of bounds...");
            $lastpos = False;
        }
        else
        {
            d("found a new tag of same kind inside tag...");
            $lastpos =  $newStartTagPos+1;       
            $endTagPos  = strpos( $source, "</".$tag, $newStartTagPos);
        }
    }

    return substr($source, $startTagEndPos, $endTagPos-$startTagEndPos);
}
?>
<html>

    <body>
    <?php

    d(GetTagContents('<div>1111<div>2222</div>3333</div>', "div", 0));

    ?>
    </body>

</html>

有人有任何想法嗎?

使用PHP DOM:

$src = new DOMDocument('1.0', 'utf-8');
$src->formatOutput = true;
$src->preserveWhiteSpace = false;
$src->load('path/to/file.html');

$tagName = 'foo';
$element = $src->getElementsByTagName($tagName)->item(0);
var_dump($element->nodValue)

strpos第一次返回0,在PHP中返回0 0 == false 您要進行的檢查是將結果與===進行比較,如果兩個值都是相同的值和相同的類型,則結果為true。 也就是說, 0 == false為真,但0 === false不為真。

你可以用它

simplexml_load_string

$xml = "[div]1111[div]2222[/div]3333[/div]";

$loadStrring = simplexml_load_string($xml);
foreach($loadStrring->children() as $name => $data) {
    if($name ='div')
        echo $data . "\n";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM