Home > Net >  htmlspecialchars can't escape " and ' in xml context
htmlspecialchars can't escape " and ' in xml context

Time:12-10

i am trying to escape 5 characters " ' < > & in xml context:

the problem is when i check the page source only < > and & is converted as expected to &lt; &gt; and &amp; but " and ' remians without change.

the php code is:

    $xml = new DOMDocument("1.0", "UTF-8");
    $rss = $xml->createElement("rss");
    $rssNode = $xml->appendChild($rss);
    $rssNode->setAttribute("version", "2.0");
    $xmlChannel = $xml->createElement("channel");
    $rssNode->appendChild($xmlChannel);
    $title = $xml->createElement("title", htmlspecialchars(" < > & ' " . '"', ENT_QUOTES | ENT_XML1, 'UTF-8'));
    $xmlChannel->appendChild($title);
    \Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
    echo $xml->saveXML();

if i change my code to this - not xml context- all 5 special characters are changed:

function() {
return htmlspecialchars(" < > & '" . '"', ENT_QUOTES | ENT_XML1, 'UTF-8');
}

why this happens? how can i escape all 5 characters?

CodePudding user response:

createElement normalises the value.

" and ' don't need to be escaped because they have no special meaning outside of attribute values delimited with those characters.

You don't need to escape them, just don't worry about it.

  • Related