Generating XML document in PHP (escape characters)

前端 未结 10 992
难免孤独
难免孤独 2020-11-27 04:20

I\'m generating an XML document from a PHP script and I need to escape the XML special characters. I know the list of characters that should be escaped; but what is the corr

10条回答
  •  暖寄归人
    2020-11-27 05:08

    Use the DOM classes to generate your whole XML document. It will handle encodings and decodings that we don't even want to care about.


    Edit: This was criticized by @Tchalvak:

    The DOM object creates a full XML document, it doesn't easily lend itself to just encoding a string on it's own.

    Which is wrong, DOMDocument can properly output just a fragment not the whole document:

    $doc->saveXML($fragment);
    

    which gives:

    Test &  and encode  :)
    Test &amp; <b> and encode </b> :)
    

    as in:

    $doc = new DOMDocument();
    $fragment = $doc->createDocumentFragment();
    
    // adding XML verbatim:
    $xml = "Test &  and encode  :)\n";
    $fragment->appendXML($xml);
    
    // adding text:
    $text = $xml;
    $fragment->appendChild($doc->createTextNode($text));
    
    // output the result
    echo $doc->saveXML($fragment);
    

    See Demo

提交回复
热议问题