POST cURL Body from File: PHP Code Examples ( JSON, CSV )

Steps to POST cURL request with a body from a File in PHP Sending a CURL request with body from file in PHP requires a few steps. You need to retrieve the content from your files, setup your curl request with curl_init, and include the CURLOPT_POSTFIELDS to the body content before executing with curl_exec. Initialize your cURL request with curl_init Open up your file content with file_get_contents Convert the file contents to a PHP array if not already. Setup your cURL Request Options array. Set CURLOPT_POST to true in options Set CURLOPT_POSTFIELDS to your PHP array from above Pass the options array to curl_setopt_array Send the cURL request with curl_exec Close the cURL request with curl_close Verify and validate response Continue processing. Post cURL Body from File in PHP Code Example <?php //Initialise the cURL var $curl = curl_init(); //Create a POST array with the file in it $fileData =…

read more

How to Return an XML response PHP Code Examples: SimpleXML

How to Return XML Response in PHP Code Example There are 2 options you can use to return an XML response in PHP. First, you want to make sure that you set appropriate headers. Secondly, you can use the file_get_contents function or the SimpleXML PHP class. We recommend the SimpleXML class when possible. Sample XML Response in PHP Code Snippet header("Access-Control-Allow-Origin: *"); header("Content-Type: text/xml; charset=UTF-8"); if(file_exists('courses.xml')) { $courses = file_get_contents('courses.xml'); echo $courses; } else { echo "&lt;?xml version=\"1.0\"?>&lt;Error>404 - File not found!&lt;/Error>"; } There are 2 keys to returning XML responses in PHP. First, you need to have a valid XML string. Secondly, you need to make sure that you have the proper headers set. It is the headers that tell your response client (browser, API, etc) that they should expect XML data. Relevant Content: HTTP Server - Request & Response In a client-server architecture, a client sends a request…

read more

How to create XML in PHP

create XML in PHP
Code Snippet: Create XML in PHP This article explores how to create XML in PHP. Here’s a solution using SimpleXMLElement class. $products = [ ["Name" => "Tomato Ketchup", "Price" => 2, "Availability" => 40], ["Name" => "Men Fragrance", "Price" => 160, "Availability" => 12], ["Name" => "Air Freshner", "Price" => 8, "Availability" => 50], ["Name" => "Cookies", "Price" => 1.5, "Availability" => 80], ]; $root = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><products/>'); foreach($products as $index => $subarray) { $product = $root->addChild('product'); //<product></product> $product->addAttribute('Id', $index); //Adds an ID attribute to the element product. foreach($subarray as $k => $v ) { $product->addChild($k, $v); //Adds name, price and availability. } } $root->asXML('products.xml'); That’s one obvious option, but that’s not the only one. We will see another class that represents DOM documents in PHP. So, stay tuned to learn something exciting today. Relevant Content: SimpleXMLElement in PHP The SimpleXMLElement class represents an XML element and defines…

read more

How to convert XML to Array or Object in PHP

XML to Array in PHP
Code Snippet: XML to Array in PHP The article explores how to convert XML to array or object in PHP. Here’s a snippet from the article. <?php $courses_xml = '&lt;courses> &lt;course> &lt;title>Fundamentals of Programming&lt;/title> &lt;credithours>3 + 1&lt;/credithours> &lt;prerequisites>None&lt;/prerequisites> &lt;/course> &lt;course> &lt;title>Object Oriented Programming&lt;/title> &lt;credithours>3 + 1&lt;/credithours> &lt;prerequisites>Fundamentals of Programming&lt;/prerequisites> &lt;/course> &lt;/courses>'; $xml = simplexml_load_string($courses_xml); $json = json_encode($xml, JSON_PRETTY_PRINT); $array = json_decode($json, true); ?> That’s just one way of going about this problem. Learn more about this topic in the following sections. Relevant Content: JSON to XML Conversion The article  “How to convert XML to JSON in PHP” sets a solid foundation for XML to array in PHP. We suggest reading that article as this article borrows alot from it. We will see that the existing solution adds only one extra function call to get an array or object, and the rest of the code is similar.  So without any further…

read more

How to Convert a PHP array to xml

Array to XML in PHP
Code Snippet: Array to XML in PHP This article answers how to convert array to XML in PHP. Here’s a snippet from the article. <?php $students_data = [ "Andy" => ["ID"=>"1001", "Electives"=>["Computer Science", "Calculus"]], "Benjamin" => ["ID"=>"1002", "Elective"=>["Electronics", "Digital Logic Design"]], "Catheline" => ["ID"=>"1003", "Elective"=>["Economics", "Political Science"]], "Dexter" => ["ID"=>"1004", "Elective"=>["Computer Science", "Discrete Mathematics"]], "Eion" => ["ID"=>"1004", "Elective"=>["Computer Science", "Digital Logic Design"]], "Franklin" => ["ID"=>"1005", "Elective"=>["Mathematics", "Physics"]], ]; function arraytoXML($arr, &$xml) { foreach($arr as $key => $value) { if(is_int($key)) { $key = 'Element'.$key; //To avoid numeric tags like <0></0> } if(is_array($value)) { $label = $xml->addChild($key); arrayToXml($value, $label); //Adds nested elements. } else { $xml->addChild($key, $value); } } } $xml = new SimpleXMLElement('&lt;?xml version="1.0" encoding="UTF-8"?>&lt;Students>&lt;/Students>'); arraytoXML($students_data, $xml); $xml->asXML('output.xml'); ?> That’s one way of doing the conversion. The article features a third-party package that will make your life a lot easier than reinventing the wheel. Stay till the end to learn more.…

read more

Convert XML to JSON Correctly With PHP Code Examples (2023)

XML to JSON in PHP
Code Snippet: XML to JSON in PHP This article focuses on converting XML to JSON in PHP. You can convert XML to JSON using 2 functions. Here's the relevant code snippet to transform XML to JSON. <?php $employees_xml = '&lt;employees> &lt;employee id="1"> &lt;firstname>Jack&lt;/firstname> &lt;lastname>Nesham&lt;/lastname> &lt;age>22&lt;/age> &lt;role>Software Engineer&lt;/role> &lt;/employee> &lt;employee id="2"> &lt;firstname>Maxwell&lt;/firstname> &lt;lastname>Rick&lt;/lastname> &lt;age>25&lt;/age> &lt;role>DevOps Engineer&lt;/role> &lt;/employee> &lt;/employees>'; $xml = simplexml_load_string($employees_xml); $json = json_encode($xml, JSON_PRETTY_PRINT); ?> That's not the only way, though. This is a solid solution in many cases, but you may encounter a more complex situation, need more flexibility, or you need this in several locations. There is a solid 3rd party composer package to convert XML to CSV which we'll discuss further in the article. Relevant Content: XML & JSON Conversion Converting PHP XML to JSON In the article, “How to convert JSON to XML in PHP”,  we learned about SimpleXMLElement class and json_decode function that helps in…

read more

Convert JSON to XML Correctly with PHP Code Examples (2023)

JSON to XML in PHP
Converting JSON to XML in PHP Code Example <?php $JSON_arr = json_decode($JSON, true); $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>'); function arraytoXML($json_arr, &$xml) { foreach($json_arr as $key => $value) { if(is_int($key)) { $key = 'Element'.$key; //To avoid numeric tags like <0></0> } if(is_array($value)) { $label = $xml->addChild($key); arrayToXml($value, $label); //Adds nested elements. } else { $xml->addChild($key, $value); } } } arraytoXML($JSON_arr, $xml); print_r($xml->asXML('output.xml')); ?> Can't understand what's going on? Don't worry, just stay tuned as this article will explain every bit in depth.  Background: JSON, XML, SimpleXMLElement Class JSON vs XML JSON and XML have some similarities and differences in structure and function. Both are popular as data exchange formats in a client-server setup. That's why applications that deal with both formats often need interconversion functionality between JSON and XML. Follow the link to learn more about JSON vs XML. This article focuses on PHP JSON to XML conversion.  PHP SimpleXMLElement…

read more

PHP serialize vs json_encode

php serialize vs json_encode
Data formats are interchangeable and this allows you to move back and forth between different data formats. This data transformation is usually necessary for data storage, transfer, and communication over a network in computers. The two most renowned data formats are JSON, XML, and CSV. JSON is quite common these days as RESTful APIs use JSON, thus many applications use JSON data to communicate with servers. The image below shows a glimpse of a computer communicating with a server using JSON data. Many programming languages feature a built-in serialization interface that provides features for data transformation, usually specific to a programming language. Unlike JSON, XML, and CSV, serialized data is in the form of an encoded text, as we’ll see later.  In this article about PHP serialize vs json_encode, we’ll explore serialization in PHP. We’ll see serialize function and compare it to json_encode. So, let’s move forward without any further…

read more

Recursive Loop Multidimensional JSON Arrays in PHP | GeoJSON

json array with PHP
How to Iterate JSON Arrays in PHP Using a Recursive Function with GeoJSON Load and set your GeoJSON content into a PHP variable Use json_decode to convert the JSON content into a php multidimensional array Create a custom recursive function to iterate the JSON content Run a while loop inside the custom function and call itself when it has children Run a foreach loop on your root array from your geojson content Create a new RecursiveArrayIterator class inside the loop Call your custom recursive function and pass in your RecursiveArrayIterator class Continue working and processing your GeoJSON array PHP Code Example: Loop Through a Multidimensional JSON Array using recursion and a foreach loop with GeoJSON //Fetches the GeoJSON array. $geojson = file_get_contents("sampleGeoJSON.json",false); //Converts GeoJSON into an associative array. $geojson_array = json_decode($geojson,true); //A recursive function to traverse the GeoJSON array. function traverseGeoJSON($iterator) { //If there is a property left. while (…

read more