dongmu1989
dongmu1989
采纳率0%
2018-04-23 14:22

使用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条回答

  • douqian7634 douqian7634 3年前

    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>
    
    点赞 评论 复制链接分享