我有一个问题,我在php编写自己的帮助类,但我想在DOM(文档)中移动标签/元素,例如,我想将head标签和js移动到底部体...
(做类似$(“link”)。appendTo(“head”)。remove(); in jquery)
我该怎么办? 我知道在PHP中存在一个DOMDocument API, 如果可以做到这一点,我想举个例子。
感谢您的帮助。
(抱歉我的英语不好,我是法国人......)
答案 0 :(得分:2)
我创建了一个库,允许您像使用jQuery一样抓取HTML5和XML文档。
你可以找到它here。
它应该让你完全按照自己的意愿行事!
使用示例:
namespace PowerTools;
// Get file content
$htmlcode = file_get_contents( 'https://github.com' );
// Define your DOMCrawler based on file string
$H = new DOM_Query( $htmlcode );
// Define your DOMCrawler based on an existing DOM_Query instance
$H = new DOM_Query( $H->select('body') );
// Passing a string (CSS selector)
$s = $H->select( 'div.foo' );
// Passing an element object (DOM Element)
$s = $H->select( $documentBody );
// Passing a DOM Query object
$s = $H->select( $H->select('p + p') );
// Select the body tag
$body = $H->select('body');
// Combine different classes as one selector to get all site blocks
$siteblocks = $body->select('.site-header, .masthead, .site-body, .site-footer');
// Nest your methods just like you would with jQuery
$siteblocks->select('button')->add('span')->addClass('icon icon-printer');
// Use a lambda function to set the text of all site blocks
$siteblocks->text(function( $i, $val) {
return $i . " - " . $val->attr('class');
});
// Append the following HTML to all site blocks
$siteblocks->append('<div class="site-center"></div>');
// Use a descendant selector to select the site's footer
$sitefooter = $body->select('.site-footer > .site-center');
// Set some attributes for the site's footer
$sitefooter->attr(array('id' => 'aweeesome', 'data-val' => 'see'));
// Use a lambda function to set the attributes of all site blocks
$siteblocks->attr('data-val', function( $i, $val) {
return $i . " - " . $val->attr('class') . " - photo by Kelly Clark";
});
// Select the parent of the site's footer
$sitefooterparent = $sitefooter->parent();
// Remove the class of all i-tags within the site's footer's parent
$sitefooterparent->select('i')->removeAttr('class');
// Wrap the site's footer within two nex selectors
$sitefooter->wrap('<section><div class="footer-wrapper"></div></section>');
[...]
支持的方法:
答案 1 :(得分:0)
您可以使用removeChild和appendChild来执行此操作
答案 2 :(得分:0)
我稍后会制作一个块系统,因为它太复杂了。 简单地说,我为链接标记做了这个:
/* set view as html string */
ob_start();
require $view;
$html = ob_get_clean();
/* DOM */
$dom = new DOMDocument();
$dom->loadHTML($html);
$_head = $dom->getElementsByTagName("head")->item(0);
$links = $dom->getElementsByTagName("link");
foreach($links as $link) {
$_head->appendChild($link);
}
$html = $dom->saveHTML();
/* render */
echo $html;