I am trying to write a PHP script that retrieves an xml file from a webservice. I have gotten an equivalent working in C#, but my overall goal is to integrate my final script into WordPress.
The trick is that I need to add an authentication header token.
In Fiddler, the request looks something like this:
GET https://service.domain.com/sample/stuff/555/state/PA/page/1/size/10 HTTP/1.1
User-Agent: Fiddler
Authorization: 123456789-123456789abcdef
Host: service.mywebgrocer.com
The C# code that I have (working) looks like:
HttpWebRequest request =
(HttpWebRequest)
WebRequest.Create("https://service.domain.com/sample/stuff/555/state/PA/page/1/size/10");
request.Method = "GET";
request.Headers.Add("Authorization", "123456789-123456789abcdef");
request.ContentType = "application/xml; charset=utf-8";
HttpWebResponse httpWebResponse = (HttpWebResponse) request.GetResponse();
Stream stream = httpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader(stream);
String streamString = streamRead.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(streamString);
Console.WriteLine("Name of xml document: {0}", doc.Name);
Console.WriteLine("outer xml: {0}\n", doc.OuterXml);
What is the best way to implement this in PHP?
Thanks!
The best way would be to use cURL, because you want the ability to pass headers.
file_get_contentswon’t allow that. Make sure you take a look at the curl_setopt function for all of the stuff you can do with cURL.I think you’ll want the option
CURLOPT_HTTPHEADER. which takes an array of HTTP header fields to set, in the formatarray('Content-type: text/plain', 'Content-length: 100').CURLOPT_USERAGENTwill allow you to pass a user agent string if you choose to do so like Fiddler does (name it something other than Fiddler).When you run
curl_execit should return the XML from the site. From there you could use the XML Parser, SimpleXML, or whatever you want.