How to Send XML Data to API With Curl PHP

Being a web developer you must need to know how to send data to API in PHP. We send data to web services using curl in PHP programming language. In this tutorial, we will see how to send XML Data to web services using curl in PHP.

In API integration, we need to send request to web services and receive response. So let us see how to send XML Data to API with PHP curl or how to send xml data to web api or how to post xml data to web app or how to post xml data to url in php.

<?php
       $xmldata = '<?xml version="1.0" encoding="UTF-8"?>
					<student>
					<info>
					<name>Rahul kumar</name>
					<age>10</age>
					<class>5th</class>
					<rollno>25</rollno>
					</info>
					</student>';


        $url = "https://www.website.com/ws";

        $ch = curl_init();
        if (!$ch) {
            die("Couldn't initialize a cURL handle");
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_POST, true);
       curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch); // execute
	echo $result;             //show response
	curl_close($ch);


?>

1 thought on “How to Send XML Data to API With Curl PHP”

Leave a Comment