1 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是gurl
和之間的一個(gè)很大區(qū)別g:url
。gurl
不是有效的 RSS 標(biāo)簽 afaik。g:url
是已url
定義命名空間內(nèi)的元素。
在g
從g:url
一個(gè)命名空間前綴。它引用了命名空間定義。xmlns:g
在示例中查找屬性或在格式文檔中查找名稱空間 URI。的g
是該屬性的值的別名。解析器在內(nèi)部將其解析為 URI。以下所有節(jié)點(diǎn)都可以讀作{urn:example:namespace}url
.
<g:url xmlns:g="urn:example:namespace"/>
<g2:url xmlns:g2="urn:example:namespace"/>
<url xmlns="urn:example:namespace"/>
RSS 本身只是格式良好的 XML,它不使用命名空間。但它可以包含使用名稱空間的其他 XML 格式(MediaRSS,...)。
要?jiǎng)?chuàng)建具有命名空間的元素,請(qǐng)使用方法DOMDocument::createElementNS()
。如果需要,這將自動(dòng)添加命名空間定義。但是,如果不使用文檔元素的命名空間,它將被添加多次。您可以將命名空間定義設(shè)置為保留的 XMLNS 命名空間的屬性。
$data = ['one', 'two'];
// the namespace for namespace definitions
const XMLNS_XMLNS = 'http://www.w3.org/2000/xmlns/';
// namespace referenced by prefix g?
const XMLNS_G = 'urn:example:namespace';
$document = new DOMDocument('1.0','utf-8');
$rss = $document->appendChild(
$document->createElement('rss')
);
// add the namespace definition to the document element
$rss->setAttributeNS(XMLNS_XMLNS, 'xmlns:g', XMLNS_G);
// create + append element node, set its text content
$rss->appendChild(
$document->createElement('title')
)->textContent = 'test';
foreach ($data as $value) {
$item = $rss->appendChild(
$document->createElement('item')
);
// create and append an element with the namespace
$item->appendChild(
$document->createElementNS(XMLNS_G, 'g:url')
)->textContent = 'http://example.com/page?'.$value;
}
$document->formatOutput = TRUE;
echo $document->saveXML();
輸出:
<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:g="urn:example:namespace">
<title>test</title>
<item>
<g:url>http://example.com/page?one</g:url>
</item>
<item>
<g:url>http://example.com/page?two</g:url>
</item>
</rss>
提示 1:DOMNode::appendChild()返回附加的節(jié)點(diǎn)??梢郧短讋?chuàng)建調(diào)用。
提示 2:DOMNode::$textContent允許讀取/寫入節(jié)點(diǎn)的文本內(nèi)容并正確轉(zhuǎn)義。
- 1 回答
- 0 關(guān)注
- 147 瀏覽
添加回答
舉報(bào)