有没有人知道如果PHP不是来自白名单数组或黑名单数组中的域,那么在PHP中采用一块文本并删除iframe?所以我可以允许像YouTube,Facebook这样的iframe,但不是每个网站.
<h3>Allowed</h3>
<iframe src="http://youtube.com" ></iframe>
<iframe src="http://www.facebook.com" ></iframe>
<iframe src="http://google.com" ></iframe>
<h3>Banned</h3>
<iframe src="http://example.com" ></iframe>
<iframe src="http://alexanderdickson.com" ></iframe>
Run Code Online (Sandbox Code Playgroud)
// Make a list of allows hosts.
$allowedHosts = array(
'youtube.com',
'facebook.com',
'google.com'
);
$dom = new DOMDocument;
$dom->loadHTML($str);
// Get all iframes in the document.
$iframes = $dom->getElementsByTagName('iframe');
$iframesLength = $iframes->length;
// Iterate over all iframes.
while ($iframesLength--) {
$iframe = $iframes->item($iframesLength);
if ($iframe->hasAttribute('src')) {
// Get the src attribute of the iframe.
$src = $iframe->getAttribute('src');
// Get the host of this iframe, to compare with our allowed hosts.
$host = parse_url($src, PHP_URL_HOST);
// If not host, then skip this iframe.
if ($host === NULL) {
continue;
}
// Strip www. because otherwise it may be 'www.facebook.com` and we have only
// banned `facebook.com`.
$host = preg_replace('/^www\./', '', $host);
// If this host is not in our allowed list, remove it from the document.
if ( ! in_array($host, $allowedHosts)) {
$iframe->parentNode->removeChild($iframe);
}
}
}
echo $dom->saveHTML();
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<h3>Allowed</h3>
<iframe src="http://youtube.com"></iframe>
<iframe src="http://www.facebook.com"></iframe>
<iframe src="http://google.com"></iframe>
<h3>Banned</h3>
</body></html>
Run Code Online (Sandbox Code Playgroud)
如果你不想返回的HTML裹着所有html,body等等,然后运行在年底这段代码...
$html = '';
foreach($dom->getElementsByTagName('body')->item(0)->childNodes as $node) {
$html .= $dom->saveXML($node, LIBXML_NOEMPTYTAG);
}
Run Code Online (Sandbox Code Playgroud)
如果你有> = PHP 5.3.6,请用saveXML()上面的替换saveHTML().
是否可以编辑
$iframe->parentNode->removeChild($iframe);替换iframe?
是的,用......替换整个块
// Create video element
$video = $dom->createElement('video');
// Attach whatever you need to...
$video->setAttribute('src', 'whatever');
// Get a reference to the parent of the iframe
$parent = $iframe->parentNode;
// Insert the video element before the iframe
$parent->insertBefore($video, $iframe);
// Remove the iframe
$parent->removeChild($iframe);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1833 次 |
| 最近记录: |