php - 使用 PHP 在 dom 中移动标签/元素

标签 php html jquery dom htmlelements

我有一个问题,我正在用 php 编写自己的帮助类,但我想移动 DOM(文档)中的标签/元素,例如,我想将 head 中的 link 标签和 js 中的 bottom body ……

(像 $("link").appendTo("head").remove(); 在 jquery 中那样做)

我该如何继续? 我知道在 PHP 中存在一个 DOMDocument API, 如果可以的话,我想要一个例子。

感谢您的帮助。

(抱歉我的英语不好,我是法国人...)

最佳答案

我创建了一个库,让您可以像使用 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. 重命名为“select”,原因很明显
  2. 重命名为“void”,因为“empty”是 PHP 中的保留字

关于php - 使用 PHP 在 dom 中移动标签/元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31314131/

相关文章:

php - 用于创建 HTML 5/Javascript 统计页面和图表的最佳开放库

html - 基础顶部栏下拉 z-index 问题

javascript - 如何在 POST 方法之后使用 javascript 更改 HTML 内容

php - 带连接的 is_object 不能正常工作?

php - 多个mysql在一个查询中选择,然后分别访问它们

javascript - 是否有 HTML api 允许我在 "#route"上显示 div 容器?

javascript - Ajax 调用仅进行一次 ASP.Net MVC5

javascript - 在 Ajax 加载页面中加载 javascript

jquery - 如何使用 jquery 淡入淡出背景图像(来自 CSS)

php - 在 GitHub 上使用 Composer 和 Private Repository 在 Build Server 上使用 VCS