- Function file_get_contents() : function file_get_contents() is used to read a file as a string. This feature uses memory mapping methods supported by the server and thus improves performance by making it the preferred way to read file content.
- The simplexml_load_string() function :Sometimes it becomes necessary to parse XML data into PHP. There are several methods for parsing XML data. SimpleXML is one of them. Parsing an XML document means navigating the XML document and returning the relevant pieces of information. Currently, some APIs return JSON data, but there are still a large number of websites that return XML data. Therefore, we must master parsing an XML document if we want to use the available APIs.
- json_encode() function:json_encode() function is used to encode a JSON string and return a JSON representation values.
- json_decode() function : function json_decode() is used to decode JSON string. It converts a JSON encoded string to a PHP variable.
GFG.xml
xml
version
=
’1.0’
?>
<
firstnamedb
>
<
firstname
name
=
’Akshat’
>
<
symbol
> AK < /
symbol
>
<
code
> A < /
code
>
< /
firstname
>
<
firstname
name
=
’Sanjay’
>
<
symbol
> SA < /
symbol
>
<
code
> B < /
code
>
< /
firstname
>
<
firstname
name
=
’Parvez’
>
<
symbol
> PA < /
symbol
>
<
code
> C < /
code
>
< /
firstname
>
< /
firstnamedb
>
Step 2. Convert file to string: The XML file will be imported into PHP using the file_get_contents() function, which reads the entire file as a string and saves it to a variable.Step 3. Convert the string to an object. Convert a string to an object, which can be easily done with some of the built-in simplexml_load_string() functions in PHP.Step 4. Convert an object to JSON.The json_encode() function is used for encoding JSON strings and return the JSON representation of the value.Step 5. Decode the JSON object.The json_decode() function decodes the JSON string. It converts a JSON encoded string to a PHP variable.Example :
// path to xml file
$path
=
"GFG.xml"
;
// Read the entire file into a line
$xmlfile
=
file_get_contents
(
$path
);
// Convert XML string to object
$new
= simplexml_load_string (
$xmlfile
);
// Convert to json
$con
= json_encode (
$new
);
// Convert to associative array
$newArr
= json_decode (
$con
, true);
print_r (
$newArr
);
?>
Output: