How to Return an XML response PHP Code Examples: SimpleXML

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

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 "<?xml version=\"1.0\"?><Error>404 - File not found!</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.

Have you tried any of the following highly relevant Pluralsight PHP Courses?

We love Pluralsight because it has thousands of high-quality course content and is extremely affordable. You don’t have to pay for individual courses. It’s a really small monthly membership and you get access to the entire catalog. You can track and review all of your progress and also obtain additional certifications.


  • PHP Design Patterns
  • PHP: The Big Picture
  • PHP 8: Web Application Security
  • High-Performance PHP
  • Object-Oriented PHP

Learning Paths:

  • PHP Development Fundamentals

Pluralsight Free Trial

Curious about Pluralsight but not ready to commit? We understand. We were able to get a free trial for you to test-drive and see all of their courses. Click on the link below

Try a Pluralsight free trial for 7 days!

Relevant Content: HTTP Server – Request & Response

In a client-server architecture, a client sends a request for data or service to a server. A server returns data in various formats, mostly in JSON or XML. We often go through this request and response cycle online without realizing it because all the granular operations happen under the hood, giving an abstract view to a user.


Suppose you’re watching your favorite show on your favorite streaming service. You are a client requesting your favorite show. The streaming service has servers that listen to your request and respond accordingly. This setup is a typical client-server architecture.

The format of data in the response can vary.

This article will set up a minimalistic HTTP server in PHP that listens to a client request and responds with XML. The main takeaway is to see PHP return XML response, but you can also see how to create a server in PHP.

Scenario: Returning XML Response in PHP using a Courses API

Background and Setup: XML response in PHP

Simply put, Application Programming Interface (API) is a piece of software that establishes a way of communication between two or more computers. In our case, we will build an API that returns some course data using an HTTP server in PHP.

The source of the data is an XML file courses.xml.

< ? xml version="1.0" ? >
    <course id="C-001">
        <title>Fundamentals of Programming</title>
        <credithours>3 + 1</credithours>
    <course id="C-002">
        <title>Object Oriented Programming</title>
        <credithours>3 + 1</credithours>
        <prerequisites>Fundamentals of Programming</prerequisites>

We need to program a script in PHP that returns this data in the form of XML when a client asks for it. But before we do that, we need to create a server that listens to clients’ requests.

Fortunately, PHP 5.4 and later versions have a built-in server for development and testing. It is by no means a full-fledged production server. You can create a WAMP or XAMPP server, but we will keep it simple here. 

Let’s create a simple PHP script first that returns a “Hello World” text as a response.

header("Access-Control-Allow-Origin: *");
header("Content-Type: text/plain; charset=UTF-8");
echo "Hello World";

Quite simple, isn’t it? The header provides metadata to the browser to give it more context about the response.

 Now is the time to create a server that listens to a client request and returns this “Hello World” text. The command to spin up a PHP server is.

php -S localhost:8000

The server is your local host that listens on port 8000. Run this command in the shell to start the server.

Development Server PHP

Now, the server is listening, and we need to make a request. Head on to your browser and type the following URL.


You’re requesting helloworld.php, and guess what you get in return?

Yes – “Hello World” from PHP in a plain text format.


Also, let’s check out the server log in the console.

PHP Server Log

See! It accepts the request and responds with a status code of 200 (Success). Once it is done serving you, it closes the request-response cycle. You can make another request now.

We have learned how to spin up a PHP server and make requests to a server. Now, let’s head to the main subject and return the XML response in PHP.

Option1: XML response in PHP using file_get_contents

One of the easiest ways is to read the XML file and return the result. To do that, we will use PHP file_get_contents function. Here’s the complete code.

header("Access-Control-Allow-Origin: *");
header("Content-Type: text/xml; charset=UTF-8");
    $courses = file_get_contents('courses.xml');
    echo $courses;
    echo "<?xml version=\"1.0\"?><Error>404 - File not found!</Error>";

The code returns the file content. If the file doesn’t exist, it returns an error response. The return type is a string, but the browser interprets that as XML because we have already specified it in the header metadata – see content-type.

Here’s the output when a client sends a request for the course data.


See! The browser receives XML as informed by the content-type option in the header.

Note: Only good for Read-Only Operations

This way of sending an XML response is good for read-only operation. Sometimes servers transform or manipulate data according to the request specifications before sending it out – for instance, request for course titles only.

Strings are not very convenient when it comes to processing and transformation. We need arrays or objects in PHP to do the necessary transformation and processing. Let’s explore how to do that.

XML response in PHP using SimpleXMLElement

In this example, we will read the file into a SimpleXMLElement object. The SimpleXMLElement object has many handy functions to parse the XML object tree. The object opens up many ways of working with the data before sending it out to the client.

header("Access-Control-Allow-Origin: *");
header("Content-Type: text/xml; charset=UTF-8");
    $courses = simplexml_load_file('courses.xml'); //The courses is now an object
    //Manipulate or transform data.
    echo $courses->asXML(); //Converts to xml and returns
    echo (new SimpleXMLElement("<?xml version=\"1.0\"?><Error>404 - File not found!</Error>"))->asXML();

Voila! Pretty much the same thing, except that we now read the file using simplexml_load_file. It returns a SimpleXMLElement object. We can perform transformations on the data – although we don’t do any here. 

Once everything is set, we send it out in XML by calling the asXML function.

The asXML function returns an XML string from the object. The output is the same as seen in the snapshot above.

We are good to go, it’s time for the wrap-up.

Returning XML in PHP Code Examples

This article explores how to return XML responses in PHP. The article gives a broad overview of client-server architecture and APIs. Once the context is set, it demonstrates an HTTP server in PHP. Building on that, it creates a server that returns course data in XML. The article includes two options for sending XML in PHP.

The first option uses the file_get_contents function in PHP, and this option fits in a read-only request scenario. When data transformation or processing is involved, it is good to process with the second option, which uses simplexml_load_file to return an object.

Classes and Functions Related to Returning XML Responses in PHP

file_get_contents: (PHP 4.3, 5, 7, 8) This is a built-in PHP function that is available from PHP 4.3 and has been included in the latest version of PHP. Given its utility and stability, the function is here to stay with no chance of depreciation anytime soon.

simplexml_load_string: (PHP 5, 7, 8) .This is a core PHP function that was first introduced in PHP 5. You should be safe to use this function as there is no concern of deprecation in the near future. It is the standard function to load an XML string into PHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.