douchan4674 2016-08-08 23:46
浏览 44
已采纳

PHP - 在DOMDocument中包含DOMDocumentFragment和未定义的命名空间

MasetrPage.xml:

<?xml version="1.0" encoding="UTF-8"?>
<PAGE
xmlns:PHOENIX = 'PHOENIX'
xmlns:PHOENIX.CORE = 'PHOENIX/CORE'
xmlns:PHOENIX.CORE.PAGE = 'PHOENIX/CORE/PAGE'
xmlns:PHOENIX.CORE.COMPILER = 'PHOENIX/CORE/COMPILER'
>
</PAGE>

Page.xml:

<PHEONIX.CORE:EXAMPLE.ELEMENT />
<PHEONIX.CORE:EXAMPLE.ELEMENT2 />

Now I want to include the Page.xml content inside the MasterPage.xml PAGE tag.

My PHP Code:

//[i] Initialize new \DOMDocument from from PageMaster.xml.
$pageDocument = \DOMDocument::load('PageMaster.xml');

//[i] Create fragment from pageDocument and append content from page XML.
$pageDocument_frag = $pageDocument->createDocumentFragment();
$pageDocument_frag->appendXML(file_get_contents('Page.xml'));

But here I get an error that the namespaces are not defined inside the Page.xml. But for my project I don't want to define the namespaces inside the Page.xml

  • 写回答

1条回答 默认 最新

  • douhui8163 2016-08-09 00:15
    关注

    If you don't define the namespaces inside the fragment string then it will not be valid XML. Namespace prefixes are both exchangeable and optional. The prefixes do not define the namespace, the xmlns*-attributes do.

    The following 3 examples all parse to the same namespace and local node name:

    • <f:foo xmlns:f="urn:foo-ns"/>
    • <foo:foo xmlns:foo="urn:foo-ns"/>
    • <foo xmlns="urn:foo-ns"/>

    All result in an element node with the local name foo and the namespace urn:foo-ns. You can read the node name as {urn:foo-ns}foo.

    However to make the XML input for users easier you can define a set prefixes for you namespaces. You take the input an wrap it into an tag that defines the namespace. After that you can parse it as a fragment and copy the childnodes.

    $xhtml = <<<'XHTML'
      <div>
        <p>Some Content.</p>
      </div>
    XHTML;
    
    $document = new DOMDocument();
    $import = $document->createDocumentFragment(); 
    $import->appendXml(
      '<section xmlns="http://www.w3.org/1999/xhtml">'.$xhtml.'</section>'
    );
    $fragment = $document->createDocumentFragment();
    foreach ($import->childNodes->item(0)->childNodes as $node) {
      $fragment->appendChild($node->cloneNode(TRUE));
    }
    
    $document->formatOutput = TRUE;
    echo $document->saveXml($fragment);
    

    Output:

    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Some Content.</p>
    </div>
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部