dongmu1989 2018-04-23 14:22 采纳率: 0%
浏览 161
已采纳

使用CDATA时,它不显示所有内容并添加结束方括号

Having created an XML feed from an API, I am aware that I have to use CDATA for a couple of the nodes. Some are working fine and without any issues, though some appear to be missing content and showing ]]> to the end.

$introduction = substr( $property['description'], 0 , 250 ); // Truncate Description at 250 characters
$description = $property['description'];

$ltd_introduction = $xml->createElement( 'introduction', htmlspecialchars( "<![CDATA[$introduction]]>" ) );
$ltd_description = $xml->createElement( 'description', htmlspecialchars( "<![CDATA[$description]]>" ) );

The newly created XML feed shows:

<introduction>
<![CDATA[Lorem ipsum dolor sit amet]]>
</introduction>
<description>
<![CDATA[Lorem ipsum dolor sit amet]]>
</description>

But on the page when it is rendered I a mixture of:

Lorem ipsum dolor sit amet

lorem ipsum dolor sit amet]]>

sit amet]]>

I'm aware there are likely to be special characters, and there are <br> which on the XML feed show as <br > Additionally, there will be letters that contain accents.

Having read various answers, I thought it necessary to add the CDATA section and htmlspecialcharacters, but still appear to be having the issues.

  • 写回答

1条回答 默认 最新

  • 普通网友 2018-04-23 19:35
    关注

    CDATA sections are a special kind of character data node without decoding. It is not the same as a normal text node. Additionally DOMDocument::createElement()s second argument is broken. It does only half the necessary escaping. A better way is to create text node or CDATA section using the corresponding methods and append it. DOM will do the escaping as needed.

    Here is an example for both node types:

    $document = new DOMDocument();
    $content = $document->appendChild($document->createElement('content'));
    
    $content
      ->appendChild($document->createElement('introduction'))
      ->appendChild($document->createTextNode('Some content & more'));
    $content
      ->appendChild($document->createElement('introduction'))
      ->appendChild($document->createCdataSection('Some content & more'));
    
    $document->formatOutput = TRUE;
    echo $document->saveXml();
    

    Output:

    <?xml version="1.0"?>
    <content>
      <introduction>Some content &amp; more</introduction>
      <introduction><![CDATA[Some content & more]]></introduction>
    </content>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题