使用 DOMDocument 创建一个定位点


Create an anchor with DOMDocument

如何使用'DOMDocument创建锚点?

<?php
$dom = new DOMDocument;
$e = $dom->createElement('a', 'link text');
$a = $dom->createAttribute('href');
$a->value = 'http://google.com';
$dom->appendChild($e);
echo $dom->saveHTML();

结果是

<a>link text</a>

属性不起作用:-/

$dom = new DOMDocument;
$e = $dom->createElement('a', 'link text');
$a = $dom->appendChild($e);
$a->setAttribute('href', 'http://google.com');
echo $dom->saveHTML();

结果是

<a href="http://google.com">link text</a>

您忘了设置属性。有了DOMAttr,这可以通过以下方法完成:

$e->setAttributeNode($a);
echo $dom->saveHTML();

您也可以直接使用

$a->setAttribute("href", "http://google.com");
<?php
$dom = new DOMDocument;
$e = $dom->createElement('a', 'link text');
$e->setAttribute('href', 'http://google.com');
$dom->appendChild($e);
echo $dom->saveHTML();