简体   繁体   中英

How to convert xml to array in php?

My code is like this :

$xmlstring = '<Response>
                    <Auth>
                        <UserID>test</UserID>
                        <UserIP>123</UserIP>
                        <XmlVersion>Testing Version</XmlVersion>
                    </Auth>
                    <SearchAvailRequest>
                        <CountryCd>ID</CountryCd>
                        <CityCd>JOG</CityCd>
                        <CheckIn>2016-01-08</CheckIn>
                        <CheckOut>2016-01-09</CheckOut>
                    </SearchAvailRequest>
                    <SearchAvailResponse>
                        <Hotel>
                            <HotelNo>1</HotelNo>
                            <HotelCode>321</HotelCode>
                            <HotelName>Test 1 Hotel</HotelName>
                            <RmGrade>Deluxe</RmGrade>
                            <RmGradeCode>DLX</RmGradeCode>
                        </Hotel>
                        <Hotel>
                            <HotelNo>2</HotelNo>
                            <HotelCode>212</HotelCode>
                            <HotelName>Test 2 & 1 Hotel</HotelName>
                            <RmGrade>Deluxe</RmGrade>
                            <RmGradeCode>DLX</RmGradeCode>
                        </Hotel>
                    </SearchAvailResponse>
                </Response>';

    $xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
    $json = json_encode($xml);
    $array = json_decode($json,TRUE);
    echo '<pre>';print_r($array);echo '</pre>';
?>

I want to convert the XML to PHP array. But I found an error like this :

Warning: simplexml_load_string(): Entity: line 24: parser error : xmlParseEntityRef: no name in C:\xampp\htdocs\ngetest\xml.php on line 268

Warning: simplexml_load_string(): <HotelName>Test 2 & 1 Hotel</HotelName> in C:\xampp\htdocs\ngetest\xml.php on line 268

Warning: simplexml_load_string(): ^ in C:\xampp\htdocs\ngetest\xml.php on line 268

This seems to happen because there is exist and symbol(Test 2 & 1 Hotel). I have not found the right solution to solve this problem

Any suggestions on how I can solve this problem?

Thank you very much

Try this:

$xmlparser = xml_parser_create();
xml_parse_into_struct($xmlparser,$xmlstring,$values);
xml_parser_free($xmlparser);
print_r($values);

Hope this helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM