PHP:如何检查< p>子节点为< iframe>与DOMDocument? [英] PHP: How to check if a <p> has a child node of <iframe> with DOMDocument?
问题描述
如何使用 DOMDocument检查
? p
是否具有 iframe
的子节点
How can I check if a p
has a child node of iframe
with DOMDocument
?
例如,
<p><iframe ....></p>
我只想打印此内容,
<iframe ....>
而
<p>bla bla bal</p>
然后什么也不做,或者只打印p内的任何内容,
then do nothing or just print whatever inside the p,
<p>bla bla bal</p>
或者,
<p>bla bla <b>bal</b></p>
然后什么也不做,或者只打印p内的任何内容,
then do nothing or just print whatever inside the p,
<p>bla bla <b>bal</b></p>
我的PHP,
$dom = new DOMDocument;
$dom->loadHTML($item_html);
if($dom->getElementsByTagName('p')->length > 1 )
{
...
}
else // if it is only a single paragraph... then do what I want above...
{
foreach ($dom->getElementsByTagName('p') as $node)
{
if ($node->hasChildNodes())
{
foreach( $dom->getElementsByTagName('iframe') as $iframe )
{
... something
}
}
else
{
...
}
}
}
有可能吗?
推荐答案
您正在尝试查找所有p元素的唯一inode元素。
You're trying to find all iframe elements that are the only childnodes of the p elements.
如果找到,您想要
/** @var DOMElement $p */
foreach ($doc->getElementsByTagName('p') as $p) {
if ($p->childNodes->length !== 1) {
continue;
}
$child = $p->childNodes->item(0);
if (! $child instanceof DOMElement) {
continue;
}
if ($child->tagName !== 'iframe') {
continue;
}
$p->parentNode->insertBefore($child, $p);
$p->parentNode->removeChild($p);
}
此foreach循环仅遍历所有p个元素,忽略所有不包含的元素
This foreach loop just iterates over all p elements, ignores all that don't have a single child node that is not a DOMElement with the iframe tagname (note: always lowercase in the compare).
如果找到一个p元素,则内部iframe包含一个具有iframe标记名的非DOMElement的子节点。
If one p element is found, then the inner iframe is moved before it and then the paragraph is removed.
用法示例:
<?php
/**
* @link http://stackoverflow.com/q/19021983/367456
*/
$html = '
<p><iframe src="...."></p>
<p>bla bla bal</p>
<p>bla bla <b>bal</b></p>
<p></p>
';
$doc = new DOMDocument();
$doc->loadHTML($html);
/** @var DOMElement[] $ps */
// $ps = $;
/** @var DOMElement $p */
foreach ($doc->getElementsByTagName('p') as $p) {
if ($p->childNodes->length !== 1) {
continue;
}
$child = $p->childNodes->item(0);
if (!$child instanceof DOMElement) {
continue;
}
if ($child->tagName !== 'iframe') {
continue;
}
$p->parentNode->insertBefore($child, $p);
$p->parentNode->removeChild($p);
}
// output
foreach ($doc->getElementsByTagName('body')->item(0)->childNodes as $child) {
echo $doc->saveHTML($child);
}
演示并输出:
<iframe src="...."></iframe>
<p>bla bla bal</p>
<p>bla bla <b>bal</b></p>
<p></p>
希望这会有所帮助。
这篇关于PHP:如何检查< p>子节点为< iframe>与DOMDocument?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!