I have a PHP variable that contains a string which represents an XML structure. This string contains ilegal characters that dont let me build a new SimpleXMLElement object from the string. I dont have a way to ask the source of the content to modify their response, so I need to execute some cleaning on this string before I create a SimpleXMLElement object.
I believe the character causing the problem is a (0x00 (00) HEX) character, and its located within one of the Text Nodes of this string XML.
What is the best way to remove this character or other characters that could break the SimpleXMLElement object.
Using the -d switch we delete a character. A backslash followed by three 0's represents the null character. This just deletes these characters and writes the result to a new file.
line = line. rstrip() will do the job. Unlike strip(), rstrip() only removes trailing whitespace characters. I tried it with null spaces on REPL and it worked.
A short answer: you could use the String. replace() method to replace the 0 character with another character, or the replaceAll() method to replace it with an empty String.
string. replace("null", ""); You can also replace all the instances of 'null' with empty String using replaceAll.
$text = str_replace("\0", "", $text);
will replace all null characters in the $text
string. You can also supply arrays for the first two arguments, if you want to do multiple replacements.
trim() will also remove null characters, from either end of the source string (but not within).
$text = trim($text);
I've found this useful for socket server communication, especially when passing JSON around, as a null character causes json_decode() to return null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With