开发者

PHP - GET tag from url

I want to get a specific tag from url, from example:

If I have this content:

<div id="hey">
   <div id="bla"></div>
</div>

<div id="hey">
   <div id="bla"></div>
</div&开发者_运维百科gt;

And I want to get all divs with the id "hey", ( i think its with preg_match_all ), How can I do that?

  • The content inside the tag can be changed.


I recommend use DOMDocument class instead of regular expressions (is less resource consumer and more clear IMHO).

$content = '<div id="hey">
   <div id="bla"></div>
</div>

<div id="hey">
   <div id="bla"></div>
</div>';

$doc = new DOMDocument();
@$doc->loadHTML($content); // @ for possible not standard HTML
$xpath = new DOMXPath($doc);
$elements = $xpath->query("//div[@id='hey']");

/*@var $elements DOMNodeList */
for ($i=0;$i<$elements->length;$i++) {
    /*@var $curr_element DOMElement */
    $curr_element = $elements->item($i);

    // Here do what you want with the element
    var_dump($curr_element);
}

If you want to get the content from an URL you can use this line instead to fill the variable $content:

$content = file_get_contents('http://yourserver/urls/page.php');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜