popphp/pop-dom

Pop PHP 框架的 Pop DOM 组件

4.0.3 2024-06-17 03:12 UTC

README

Build Status Coverage Status

Join the chat at https://popphp.slack.com Join the chat at https://discord.gg/TZjgT74U7E

概览

pop-dom 是一个用于生成、渲染和解析 DOM 文档和元素的组件。使用它,您可以轻松创建或解析文档节点及其子节点,并控制节点内容和属性。

pop-domPop PHP 框架 的一个组件。

顶部

安装

使用 Composer 安装 pop-dom

composer require popphp/pop-dom

或者,在您的 composer.json 文件中引用它

"require": {
    "popphp/pop-dom" : "^4.0.0"
}

顶部

快速入门

一个简单的 DOM 节点片段

use Pop\Dom\Child;

$div = new Child('div');
$h1  = new Child('h1', 'This is a header');
$p   = new Child('p');
$p->setNodeValue('This is a paragraph.');

$div->addChildren([$h1, $p]);

echo $div;
<div>
    <h1>This is a header</h1>
    <p class="paragraph">This is a paragraph.</p>
</div>

构建完整的 DOM 文档

use Pop\Dom\Document;
use Pop\Dom\Child;

// Title element
$title = new Child('title', 'This is the title');

// Meta tag
$meta = new Child('meta');
$meta->setAttributes([
    'http-equiv' => 'Content-Type',
    'content'    => 'text/html; charset=utf-8'
]);

// Head element
$head = new Child('head');
$head->addChildren([$title, $meta]);

// Some body elements
$h1 = new Child('h1', 'This is a header');
$p  = new Child('p', 'This is a paragraph.');

$div = new Child('div');
$div->setAttribute('id', 'content');
$div->addChildren([$h1, $p]);

// Body element
$body = new Child('body');
$body->addChild($div);

// Html element
$html = new Child('html');
$html->addChildren([$head, $body]);

// Create and render the DOM document with HTTP headers
$doc = new Document(Document::HTML, $html);
echo $doc;
<!DOCTYPE html>
<html>
    <head>
        <title>This is the title</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
        <div id="content">
            <h1>This is a header</h1>
            <p>This is a paragraph.</p>
        </div>
    </body>
</html>

顶部

解析

您可以从 XML 或 HTML 字符串中解析,并将返回一个包含子元素的对象,您可以进一步操作或编辑,然后输出

$html = <<<HTML
<html>
    <head>
        <title>Hello World Title</title>
    </head>
    <body>
        <h1 class="top-header" id="header">Hello World Header</h1>
        <p>How are <em>YOU</em> doing <strong><em>today</em></strong>???</p>
        <p class="special-p">Some <strong class="bold">more</strong> text.</p>
    </body>
</html>
HTML;

$doc = new Document(Document::HTML);
$doc->addChild(Child::parseString($html));
echo $doc;

您也可以从文件中解析

$children = Child::parseFile('index.html');

顶部