Creating Web Services with PHP and SOAP, Part 2

Share this article

In the first part of this series, I showed you how developing applications with the SOAP protocol is a great way to build interoperable software. I also demonstrated how easy it is to build your very own SOAP server and client using the NuSOAP library. This time around I’d like to introduce you to something that you will most definitely run into when working with SOAP – WSDL files. In this article we’ll talk about what WSDL files are and how to use them. I’ll show you how to quickly build your WSDL files with NuSOAP and incorporate a WSDL file into the SOAP server and client examples from the first part.

What are WSDL Files?

Web Services Description Language (WSDL) files are XML documents that provide metadata for a SOAP service. They contain information about the functions or methods the application makes available and what arguments to use. By making WSDL files available to the consumers of your service, it gives them the definitions they need to send valid requests precisely how you intend them to be. You can think of WSDL files as a complete contract for the application’s communication. If you truly want to make it easy for others to consume your service you will want to incorporate WSDL into your SOAP programming.

WSDL Structure

Just like SOAP messages, WSDL files have a specific schema to adhere to, and specific elements that must be in place to be valid. Let’s look at the major elements that make up a valid WSDL file and explain their uses.
<definitions>
 <types>
  ........
 </types>
 <message>
  <part></part>
 </message>
 <portType>
  .......
 </portType>
 <binding>
  ....
 </binding>
 <service>
  ....
 </service>
</definitions>
The root element of the WSDL file is the definitions element. This makes sense, as a WSDL file is by definition a definition of the web service. The types element describes the type of data used, which in the case of WSDL, XML schema is used. Within the messages
element, is the definition of the data elements for the service. Each messages element can contain one or more part elements. The portType element defines the operations that can be performed with your web service and the request response messages that are used. Within the binding element, contains the protocol and data format specification for a particular portType
. Finally, we have the service element which defines a collection of service element contains the URI (location) of the service. The terminology has changed slightly in naming some of the elements in the WSDL 2.0 specification. portType, for example, has changed its name to Interface. Since support for WSDL 2.0 is weak, I’ve chosen to go over version 1.1 which is more widely used.

Building a WSDL File

WSDL files can be cumbersome to write by hand as they must contain specific tags and are usually quite long. The nice thing about using NuSOAP is that it can create a WSDL file for you! Let’s modify the SOAP server we made in the first article to accommodate this. Open productlist.php and change it to reflect the code below:
<?php
require_once "nusoap.php";

function getProd($category) {
    if ($category == "books") {
        return join(",", array(
            "The WordPress Anthology",
            "PHP Master: Write Cutting Edge Code",
            "Build Your Own Website the Right Way"));
    }
    else {
        return "No products listed under that category";
    }
}

$server = new soap_server();
$server->configureWSDL("productlist", "urn:productlist");

$server->register("getProd",
    array("category" => "xsd:string"),
    array("return" => "xsd:string"),
    "urn:productlist",
    "urn:productlist#getProd",
    "rpc",
    "encoded",
    "Get a listing of products by category");

$server->service($HTTP_RAW_POST_DATA);
Basically this is the same code as before but with only a couple of changes. The first change adds a call to configureWSDL(); the method acts as a flag to tell the server to generate a WSDL file for our service. The first argument is the name of the service and the second is the namespace for our service. A discussion of namespaces is really outside the scope of this article, but be aware that although we are not taking advantage of them here, platforms like Apache Axis and .NET do. It’s best to include them to be fully interoperable. The second change adds additional arguments to the register() method. Breaking it down:
  • getProd is the function name
  • array("category" => "xsd:string") defines the input argument to getProd and its data type
  • array("return" => "xsd:string") defines the function’s return value and its data type
  • urn:productlist defines the namespace
  • urn:productlist#getProd defines the SOAP action
  • rpc defines the type of call (this could be either rpc or document)
  • encoded defines the value for the use attribute (encoded or literal could be used)
  • The last parameter is a documentation string that describes what the getProd function does
Now point your browser to http://yourwebroot/productlist.php?wsdl and you’ll see the brand new WSDL file created for you. Go ahead and copy that source and save it as it’s own file called products.wsdl and place it in you web directory.

Consuming WSDL Files with the Client

We’ve modified the SOAP server to generate a WSDL file, so now lets modify the SOAP client to consume it. Open up productlistclient.php created in the previous article and simply change the line that initiates the client from this:
$client = new nusoap_client("http://localhost/nusoap/productlist.php");
to this:
$client = new nusoap_client("products.wsdl", true);
The second parameter in the nusoap_client() constructor call tells NuSOAP to build a SOAP client to accept the WSDL file. Now launch productlistclient.php in your browser and you should see the same result as before, but now you’re using WSDL power!

Summary

In part 2 of this series on creating web services with PHP and SOAP, we went over the importance of using WSDL files for optimum interoperability. We talked about the different elements that make up a WSDL file and their definitions, and then I showed you how to quickly and easily create your own WSDL files with the NuSOAP library. Finally, we modified our SOAP server and client to demonstrate how to use WSDL in your applications. As you can probably guess, I’ve just barely scraped the surface of what SOAP can do for you, but with these new tools you can provide an easy and well-accepted way of exposing web services to your users. Comments on this article are closed. Have a question about PHP? Why not ask it on our forums? Image via Lilyana Vynogradova / Shutterstock

Frequently Asked Questions (FAQs) about Web Services with PHP and SOAP

What is the role of WSDL in SOAP-based web services?

WSDL, or Web Services Description Language, plays a crucial role in SOAP-based web services. It is an XML-based interface definition language that is used for describing the functionality offered by a web service. In simpler terms, it is like a contract that defines what the web service does and how it should be called. It includes details like the methods the service exposes, the format of the input and output messages, the transport protocol to be used (usually HTTP), and the location of the service.

How can I handle SOAP faults in PHP?

SOAP faults are errors that occur during the processing of a SOAP message. In PHP, you can handle SOAP faults using the try-catch block. When a SOAP fault occurs, the PHP SOAP extension throws a SoapFault exception that you can catch and handle appropriately. The SoapFault exception provides methods to get the fault code, fault string, and other details about the fault.

What is the difference between SOAPClient and SOAPServer in PHP?

In PHP, SOAPClient and SOAPServer are two classes provided by the SOAP extension. SOAPClient is used to send requests to a SOAP-based web service. It provides methods to call the service methods and handle the responses. On the other hand, SOAPServer is used to create a SOAP-based web service. It provides methods to define the service methods and handle incoming requests.

How can I use SOAP headers in PHP?

SOAP headers are optional elements in a SOAP message that can be used to provide additional information that is not part of the payload. In PHP, you can use the SoapHeader class to create SOAP headers. You can add the SoapHeader object to the SOAP message using the __setSoapHeaders method of the SOAPClient class.

How can I debug SOAP requests and responses in PHP?

Debugging SOAP requests and responses in PHP can be done using the built-in features of the SOAP extension. The SOAPClient class provides the __getLastRequest and __getLastResponse methods that return the last SOAP request and response as XML strings. You can use these methods to inspect the SOAP messages and identify any issues.

How can I handle complex types in SOAP with PHP?

Handling complex types in SOAP with PHP can be done using the classmap option of the SOAPClient class. The classmap option allows you to map WSDL types to PHP classes. This way, when a complex type is received in a SOAP response, it is automatically converted to the corresponding PHP object.

What is the role of namespaces in SOAP?

Namespaces in SOAP are used to avoid element name conflicts. They are similar to packages in programming languages. A namespace is defined using a URI, and each element in a SOAP message can be associated with a namespace.

How can I use SOAP with HTTPS in PHP?

Using SOAP with HTTPS in PHP requires setting up the stream context with the appropriate SSL options. This can be done using the stream_context_create function and the stream_context option of the SOAPClient class.

How can I handle attachments in SOAP with PHP?

Handling attachments in SOAP with PHP can be done using the SOAP extension’s support for MIME and DIME attachments. You can add attachments to a SOAP message using the addAttachment method of the SOAPClient class.

How can I handle SOAP version mismatches in PHP?

SOAP version mismatches in PHP can be handled by specifying the SOAP version in the options array when creating a SOAPClient or SOAPServer object. The SOAP extension supports both SOAP 1.1 and SOAP 1.2, and you can switch between them as needed.

Stephen ThorpeStephen Thorpe
View Author

Stephen Thorpe is originally from London but now living in Tennessee. He works at an Internet and Telephone company as an applications developer primarily using PHP and MySQL.

Advanced
Share this article
Read Next
How Top HR Agencies Build Trust Through Logo Designs
How Top HR Agencies Build Trust Through Logo Designs
Evan Brown
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
SitePoint Sponsors
10 Artificial Intelligence APIs for Developers
10 Artificial Intelligence APIs for Developers
SitePoint Sponsors
The Ultimate Guide to Navigating SQL Server With SQLCMD
The Ultimate Guide to Navigating SQL Server With SQLCMD
Nisarg Upadhyay
Retrieval-augmented Generation: Revolution or Overpromise?
Retrieval-augmented Generation: Revolution or Overpromise?
Kateryna ReshetiloOlexandr Moklyak
How to Deploy Apache Airflow on Vultr Using Anaconda
How to Deploy Apache Airflow on Vultr Using Anaconda
Vultr
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 10 Best WordPress AI Plugins of 2024
Top 10 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
The Best React Chart Libraries for Data Visualization in 2024
The Best React Chart Libraries for Data Visualization in 2024
Dianne Pena
7 Free AI Logo Generators to Get Started
7 Free AI Logo Generators to Get Started
Zain Zaidi
Turn Your Vue App into an Offline-ready Progressive Web App
Turn Your Vue App into an Offline-ready Progressive Web App
Imran Alam
Clean Architecture: Theming with Tailwind and CSS Variables
Clean Architecture: Theming with Tailwind and CSS Variables
Emmanuel Onyeyaforo
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form