php 动态生成dom
时间: 2023-09-08 19:10:18 浏览: 44
PHP可以通过DOM扩展库来操作XML和HTML文档,实现动态生成DOM。下面是一个简单的例子:
```php
// 创建一个空的HTML文档
$dom = new DOMDocument('1.0', 'utf-8');
$html = $dom->createElement('html');
$dom->appendChild($html);
// 创建<head>元素
$head = $dom->createElement('head');
$html->appendChild($head);
// 创建<title>元素
$title = $dom->createElement('title', '动态生成DOM示例');
$head->appendChild($title);
// 创建<body>元素
$body = $dom->createElement('body');
$html->appendChild($body);
// 创建<h1>元素
$h1 = $dom->createElement('h1', 'Hello, World!');
$body->appendChild($h1);
// 输出HTML文档
echo $dom->saveHTML();
```
这段代码会输出一个简单的HTML文档:
```html
<!DOCTYPE html>
<html>
<head>
<title>动态生成DOM示例</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
```
你可以根据需要,使用DOM扩展库提供的方法来添加、删除、修改DOM元素,从而实现更复杂的HTML文档生成。