Created
July 22, 2015 11:31
-
-
Save ryanfitton/06831bb1a26b8e6bade3 to your computer and use it in GitHub Desktop.
Convert Reserved XML charecters to Entities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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("&", "<", ">", """, "'", "-"), | |
$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