如何使用DOMDocument获取标记内容?

时间:2022-10-27 07:53:07

Say this is the HTML?

说这是HTML吗?

<html>
<body>
<embed scr="...." attr="..."></embed>
</body>
</html>

I want to match whole embed tag <embed scr="...." attr="..."></embed>. How can I do so?

我想匹配整个嵌入标记。我怎么能这样做?

I got this far

我到目前为止

$fragment = new DOMDocument();
$fragment->loadHTML($string);

$xp = new DOMXPath($fragment);
$result = $xp->query("//embed");
print_r($result->item(0));

2 个解决方案

#1


7  

Like this:

<?php
$fragment = new DOMDocument();
$fragment->loadHTML($string);

foreach ($fragment->getElementsByTagName("embed") as $element) 
{
    echo $fragment->saveXML($element);
}
?>

#2


2  

You could take a look at this PHP Class.

你可以看看这个PHP类。

If I understood your problem correctly. Doing it with this class would be as simple as:

如果我理解你的问题。使用这个类就可以这么简单:

$html = str_get_html($string);
$ret = $html->find('embed');

EDIT. And the same thing in phpQuery:

编辑。和phpQuery一样:

phpQuery::newDocumentHTML($string);
$ret = pq('embed');

You should look into this post of Gordon by the way.

你应该顺便看一下戈登的这篇文章。

#1


7  

Like this:

<?php
$fragment = new DOMDocument();
$fragment->loadHTML($string);

foreach ($fragment->getElementsByTagName("embed") as $element) 
{
    echo $fragment->saveXML($element);
}
?>

#2


2  

You could take a look at this PHP Class.

你可以看看这个PHP类。

If I understood your problem correctly. Doing it with this class would be as simple as:

如果我理解你的问题。使用这个类就可以这么简单:

$html = str_get_html($string);
$ret = $html->find('embed');

EDIT. And the same thing in phpQuery:

编辑。和phpQuery一样:

phpQuery::newDocumentHTML($string);
$ret = pq('embed');

You should look into this post of Gordon by the way.

你应该顺便看一下戈登的这篇文章。