How to save XML API response into MySQL Database using PHP

When you integrate XML API then expected response is in XML format.  PHP has a built-in function “simplexml_load_string” which interprets an input XML into the object, but this way you can’t save it in a database.

When you want to save any XML API response or any XML read from XML text file, you need to first identify field for a database.

If you have fixed format XML then the better way is you can create a separate table and save the content of XML API response or XML text file into that table. But in the majority of the case when you integrate XML API in PHP chances of different formatted XML is most obvious and at that time dedicated tables for each type of response is not the ideal solution.

Here we need to have a single column with text type having XML response which should be easy to retrieve and parse in future.

One way to do so is converting XML API response into PHP Objects by using “simplexml_load_string” function and then convert the object into JSON by using “json_encode” function.

As shown below is sample code snippet to save XML API response in database column as text filed by converting into JSON using PHP.

xml_response_in_mysql_db_php_xml_to_json

$rg_resp_data = $this->sample_model->post_xml_request(); // Call an API and get XML Response
$rg_resp_data = simplexml_load_string($rg_resp_data); // Convert XML Response into PHP Objects
$xml_string =  json_encode($rg_resp_data); // Convert Objects into JSON and get String
$query = "insert into test values ".$xml_string ; // insert json string into column

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!