Skip to content

Instantly share code, notes, and snippets.

@ryanfitton
Created July 22, 2015 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanfitton/06831bb1a26b8e6bade3 to your computer and use it in GitHub Desktop.
Save ryanfitton/06831bb1a26b8e6bade3 to your computer and use it in GitHub Desktop.
Convert Reserved XML charecters to Entities
<?php
/*
Convert Reserved XML charecters to Entities
http://stackoverflow.com/questions/1132633/converting-to-amp-for-xml-in-php
*/
function xml_convert($str, $protect_all = FALSE) {
$temp = '__TEMP_AMPERSANDS__';
// Replace entities to temporary markers so that
// ampersands won't get messed up
$str = preg_replace("/&#(\d+);/", "$temp\\1;", $str);
if ($protect_all === TRUE) {
$str = preg_replace("/&(\w+);/", "$temp\\1;", $str);
}
$str = str_replace(
array("&","<",">","\"", "'", "-"),
array("&amp;", "&lt;", "&gt;", "&quot;", "&apos;", "&#45;"),
$str
);
// Decode the temp markers back to entities
$str = preg_replace("/$temp(\d+);/","&#\\1;",$str);
if ($protect_all === TRUE) {
$str = preg_replace("/$temp(\w+);/","&\\1;", $str);
}
return $str;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment