0

I'm creating a XML object using PHP SimpleXMLElement

I have the full XML in $RAWResponse, so I use

$oXMLResponse = new SimpleXMLElement($RAWresponse);

The XML I'm getting comes from a webservice. I detected the XML contains invalid chars, as '&' for instance.

There are a lot of posts about this issue but none works. I tried htmlentities() but this escapes every char, including the '<' and '>' opening and enclosing the XML Elements.

Finally I used this function :

$some_special_chars = array("&");
$replacement_chars  = array("&amp;");
$RAWresponse    = str_replace($some_special_chars, $replacement_chars, $RAWresponse);

$oXMLResponse = new SimpleXMLElement($RAWresponse);

This works but it's a stupid solution, because it will break if I get any other special char. Is there a better solution? I cant understand why SimpleXMLElement breaks, it should only show a warning or something.

hakre
  • 193,403
  • 52
  • 435
  • 836
Alex Angelico
  • 3,710
  • 8
  • 31
  • 49
  • Please make use of any of the existing answers to your question before asking it. If all of those do not work for you, please make visible in your question which solutions you have tried so far and why they do not apply in your case. – hakre Apr 19 '13 at 07:51

1 Answers1

1

This is not possible using PHP's built in SimpleXML extension (Or even the DOM extension). You must either replace all invalid characters with their proper entities or request that the web-service provider return valid XML.

Brandon
  • 16,382
  • 12
  • 55
  • 88