Home >Backend Development >PHP Tutorial >Solution to encounter < and > when parsing xml when php calls webservice
When I was working on a small project recently, I needed to retrieve some data from the hospital system, which only provided xml data from the webservice.
On the last day of program debugging, when I was about to demonstrate, I found that there was an extra '<' in the xml, which caused the xml to be unable to be parsed. I found many ways!
1. Use the stripos() function to locate the starting position of the included xml tag.
2. Intercept the tag through the substr() function
3. Replace it through the str_replace() function.
Although this method is a bit cumbersome, the idea is still very clear, but later I found that this method is not very useful if there are multiple tags in the xml that contain '<'.
So, I thought of the regular callback method:
function search($match){
$match = str_replace("<", "@", $match[1]);
return $match;
}
//$xml = simplexml_load_file("tes.xml"); //Read xml file
$xml_str=file_get_contents("test.xml");
$xml_result=preg_replace_callback("/(.*? :
The main thing is to use regular callbacks to replace the angle brackets < with @, and then replace @ back with <
The above introduces the solution to the problem of parsing xml when calling webservice in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.