Reading a SharePoint list with PHP (updated)
Updated (March 4, 2010): Added an example that uses the PHP5 built-in SOAP support instead of the NuSOAP library.
![]()
![]()
In my previous posts I showed a way to interact with SharePoint’s Lists Web Service through a Java application. Today I’d like to show how to do similar basic tricks with PHP. Once again, toying with SharePoint Web Services from a non-Microsoft language isn’t exactly a walk in the park.
I tried to do some experiments lately: I managed to read a SharePoint Online List from PHP, thanks to the nusoap library and a blog post written by Craige Thomas. As usual, a lot of trouble comes from the consumption of a WSDL that lies behind an NTLM/SSL server (in the case of SharePoint Online anyways). Once again, the easiest way to avoid such problems is to download and parse the WSDL file locally (Lists.asmx). Using basic authentication is the way to go when building a simple lists reading application in PHP, solving the NTLM issue implies too many intricacies in my opinion. If you manage to do it with a simple and straightforward solution, please let me know.
The code sample below will basically display the Lists Web Service request and response (see the screenshot above). Before running the code, you’ll have to set the username, password, and the local path to your Lists WSDL file. The logical next step, if you want to manipulate the results, would be to cast the response into a DOM document and parse it for the information you’re looking for.
<?php
//Requires the NuSOAP library
require_once('lib/nusoap.php');
$username = 'yourLogin';
$password = 'yourPassword';
$rowLimit = '150';
/* A string that contains either the display name or the GUID for the list.
* It is recommended that you use the GUID, which must be between curly
* braces ({}).
*/
$listName = "yourSharePointListName";
/* Local path to the Lists.asmx WSDL file (localhost). You must first download
* it manually from your SharePoint site (which should be available at
* yoursharepointsite.com/subsite/_vti_bin/Lists.asmx?WSDL)
*/
$wsdl = "http://localhost/phpsp/Lists.wsdl";
//Basic authentication. Using UTF-8 to allow special characters.
$client = new nusoap_client($wsdl, true);
$client->setCredentials($username,$password);
$client->soap_defencoding='UTF-8';
//XML for the request. Add extra fields as necessary
$xml ='
<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>'.$listName.'</listName>
<rowLimit>'.$rowLimit.'</rowLimit>
</GetListItems>
';
//Invoke the Web Service
$result = $client->call('GetListItems', $xml);
//Error check
if(isset($fault)) {
echo("<h2>Error</h2>". $fault);
}
//Extracting and preparing the Web Service response for display
$responseContent = utf8_decode(htmlspecialchars(substr($client->response,strpos($client->response, "<"),strlen($client->response)-1)));
//Displaying the request and the response, broken down by header and XML content
echo "<h2>Request</h2><pre>" . utf8_decode(htmlspecialchars($client->request, ENT_QUOTES)) . "</pre>";
echo "<h2>Response header</h2><pre>" . utf8_decode(htmlspecialchars(substr($client->response,0,strpos($client->response, "<")))) . "</pre>";
echo "<h2>Response content</h2><pre>".$responseContent."</pre>";
//Uncomment for debugging info:
//echo("<h2>Debug</h2><pre>" . htmlspecialchars($client->debug_str, ENT_QUOTES) . "</pre>");
unset($client);
?>
And here’s the faster and cleaner version that uses the PHP5 built-in SOAP support:
<?php
//Authentication details
$authParams = array('login' => 'yourUsername',
'password' => 'yourPassword');
/* A string that contains either the display name or the GUID for the list.
* It is recommended that you use the GUID, which must be surrounded by curly
* braces ({}).
*/
$listName = "TempList";
$rowLimit = '150';
/* Local path to the Lists.asmx WSDL file (localhost). You must first download
* it manually from your SharePoint site (which should be available at
* yoursharepointsite.com/subsite/_vti_bin/Lists.asmx?WSDL)
*/
$wsdl = "http://localhost/phpsp/Lists.wsdl";
//Creating the SOAP client and initializing the GetListItems method parameters
$soapClient = new SoapClient($wsdl, $authParams);
$params = array('listName' => $listName,
'rowLimit' => $rowLimit);
//Calling the GetListItems Web Service
$rawXMLresponse = null;
try{
$rawXMLresponse = $soapClient->GetListItems($params)->GetListItemsResult->any;
}
catch(SoapFault $fault){
echo 'Fault code: '.$fault->faultcode;
echo 'Fault string: '.$fault->faultstring;
}
echo '<pre>' . $rawXMLresponse . '</pre>';
//Loading the XML result into parsable DOM elements
$dom = new DOMDocument();
$dom->loadXML($rawXMLresponse);
$results = $dom->getElementsByTagNameNS("#RowsetSchema", "*");
//Fetching the elements values. Specify more attributes as necessary
foreach($results as $result){
echo $result->getAttribute("ows_LinkTitle")."<br/>";
}
unset($soapClient);
?>

Will you posting an example of updating a Sharepoint list via PHP?
I have a specific need to add and update Sharepoint calendar entries and I prefer to use PHP and NuSoap to interact with Sharepoint web services.
I will post an update example soon, stay tuned.
Hmm it dont work, how can this code see where the server is? There is no listing in the WSDL file about the server. And no specifications in the code you provided.. im just getting a “HTTP/1.1 401 Unauthorized” in the Debug feedback..
The server location is in the wsdl file, right at the bottom:
Ohh i see the path now, but i still get the “HTTP/1.1 401 Unauthorized”
And im a admin..
I’ve tested this code with SharePoint Online, so if you have been using MOSS 2007 I won’t be able to help much.
However, you might want to check this out:
* There’s something wrong with your credentials. Try to add your domain to the login (like Admin@YourSharePointDomain.com)
* Your SharePoint server is using a particular security configuration. Here are some possible solutions : http://www.crsw.com/mark/Lists/Posts/Post.aspx?List=c0001cfc-d84a-4be0-b437-6a625925a9d5&ID=44
http://geekswithblogs.net/naijacoder/archive/2009/01/14/128679.aspx
http://andreasglaser.net/post/2009/05/10/SharePoint-2007-and-HTTP-Error-4011-Unauthorized-Access-is-denied-due-to-invalid-credentials.aspx
I hope this helps, let me know
Ok, i use Winserver 2003 and MOSS2007, and i got to work now, you have to activate “Basic authentication” in IIS6 for the site you are trying to access
And btw, thanks for this great post, its the only one of its kind out there
Thanks a lot for your code. It´s working pretty nice for me.
Greetings from Spain.
Hello,
When I start the PHP script I get the following error message:
Fault code: HTTPFault string: Forbidden
AND
Warning: DOMDocument:: loadXML () [domdocument.loadxml]: Empty string supplied as input in. ..
Does the PHP script running on the server where SharePoint 2010 is running well?
Best regards
Heiko
Hello,
I get the same empty string error, but it is because the GetListItems call on line 24 isn’t working. When it gets to line 34, $rawXMLresponse is still null.
I don’t know why it isn’t working though as I am just starting out with this also.
Heiko,
I’m sure that your getting both of those errors because you haven’t been able to authenticate to the sharepoint server. I had the same issue when using the second example, but had more luck in troubleshooting it while using the first example.
My issue is that when i return a result from the list I am retrieving, all data seems to be stored in the attributes of the rows node, and I am not used to using the DOM, so I don’t know how to iterate through all the attributes without having to supply they exact names of the attrubutes (so I haven’t been successful in making it abstract enough to load results into a new DOM in and OO way).
No, we are authenticating to get to that point, otherwise it would be a 401 Unathorized error message. Once I switched to basic auth as Juel suggested above I got past that problem.
In the first example I am getting a 500 Internal server error, but that is most likely because I don’t have the $listName set correctly. I am trying to get a list of lists because right now I am blind as to what is available on the site.
Ok, I got both working. My problem was the list name not being correct. Once I had a correct name, both examples started working.
The right-bracket on line 4 shouldn’t be there. (Sorry, call me Mr Picky!)
Thanks fot the code ! Just the right bracket on line 4 and the ; on line 5 for the code to work. But great example.
Should notice that the first part wouldn’t work on PHP 5, only the second does.
Thanks for reporting the typos, I just corrected them.
I’ve tested both code samples on PHP5, and they were working for me. Maybe it has something to do with the NuSOAP library in the first example? Anyways the second one is indeed the recommended way to go.
Thanks tor the code !!
Additional Info: Here you find Infos about getting the UID of a Sharepoint List.
http://www.dhirajranka.com/?tag=sharepoint-list-guid
Hi,
i have done everything according to the instructions and on the export page i see only empty headings:
Request
Response header
Response content
the $result variable on line #36 received FALSE value from $client->call(‘GetListItems’, $xml);
Can anyone please help?
Hi, I have full access to the subsite of sharepoint, but I am getting this response:
Fault code: HTTP
Fault string: Unauthorized
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Empty string supplied as input in /usr/local/www/apache22/data/files/testsp.php on line 41
I mean it seems obvious I’m not authorized, but I’m curious if you know of any global options that the site may be inheriting that is preventing this? Do you know of any way to check on my sharepoint site what options may be restricting this?
Thanks v. much David for the code. Works like a charm. Just to say that we use ISA to front MOSS 2007 and the code works just fine. I am also able to load the WSDL dynamically from MOSS without having to download it first.
Great!
AL
Check out the Camelot PHP Tools for SharePoint package.
Send queries directly to SharePoint from SharePoint.
$SharePointQuery = new SharePointQuery(
array(
‘sql’ => “Select * from `My SharePoint List`.`ViewName`”,
‘compression’ => true,
‘connString’ => ‘sharepoint_connection’,
‘sharedKey’ => constant(“WSDL_SHARED_KEY”)
)
);
http://blog.bendsoft.com/2011/04/camelot-php-tools-1-1-for-sharepoint-released/
…Which requires the Camelot tools be installed to get it working.
I know share-point isn’t cheap, but at least mention the dependencies in your example.
True, figured the examples in the blog post would be enough.
Anyway, the dependencies are http://www.bendsoft.com/net-sharepoint-connector/ and http://www.bendsoft.com/downloads/camelot-sharepoint-integration-toolkit/
With these tools you can create the most advanced integrations in no time!
I have used this on somewhat successfully, but I can’t get query parameter working (it just doesn’t filter anything out) and viewName parameter splashes an error message though the named view exists on SP server.
I can live with this situation but I would very much prefer the people to make their own views so all I’d need to do is to make some UI with which they could set the filtering without bothering me at all
Any hints or pointers?
Hank, if you are referring to the Camelot Solution.
If you are using a query you dont need to attach the view name at all. Just go with
‘sql’ => “SELECT id, LinkTitle AS Title FROM `Whatever List` ORDER BY LinkTitle”,
If you are using the view name as a suffix to the list name it needs to be escaped with ` signs if it contain any spaces or special characters. In example
SELECT * FROM Tasks.View
SELECT * FROM Tasks.`A view name`
SELECT * FROM `My Tasks`.`All Tasks`
However, if you want to make your selections based on the views there is an optional way to do this.
$SharePointQuery = new SharePointQuery(
array(
‘listName’ => ‘My SharePoint List’,
‘viewName’ => ‘ViewName’,
‘includeAttachements’ => false,
‘compression’ => true,
‘connString’ => ‘sharepoint_connection’,
‘columns’ => ‘ID;Title;ListItem1;ListItem2′, // optional
‘sharedKey’ => constant(“WSDL_SHARED_KEY”)
)
);
I am sorry for my vaque reference. I meant the method of the article, not that of the Camelot… Thanks for your answer though
hank
This is exactly the issue I’ve got.
I’ve tried adding a ‘query’ to the $params array — formed using CAML — but this doesn’t work. Having checked the content of the SOAP request (using $soapClient->__getLastRequest() — the isn’t included — just an empty
Any ideas how to include a query in the SOAP request?
Thanks.
I had no luck getting the query working using the PHP5 SOAP object, so ended up just using CAML, the query syntax is roughly:
[VALUE]
And goes within the Tag.
I actually created a simple PHP Object pretty recently to make all this stuff more straight forward, though its still pretty basic. You can grab it at: https://github.com/thybag/PHP-SharePoint-Lists-API/blob/master/sharepointAPI.php if your interested (ether to borrow some of the code from or use)
It seems wordpress filtered out all the CAML i posted o.0.
Here’s it on pastebin instead: http://pastebin.com/nQmd3QKi
That’s brilliant… a great help.Thanks for your efforts.
any chance that anyone has figured out to do this to Office 365′s sharepoint online? somehow it has to work with forms-based authentication and manage the FedAuth cookie through the authentication.aspx service before anything else will work…
I still can’t resolve my problem (401 – Unauthorized). I’m trying to consume a Sharepoint web service using nuSoap in PHP. Here’s part of my code:
$client = new nusoap_client($wsdl, true);
$client->setCredentials($username, $password, ‘NTLM’);
$client->setUseCurl(true);
$client->useHTTPPersistentConnection();
$client->setCurlOption(CURLOPT_USERPWD, $username.’:’.$password);
$client->soap_defencoding=’UTF-8′;
The WSDL document gets parsed well (all exposed functions correctly identified), but then I get the 401 error when I try the GetListItems call. My credentials are correct when viewing the Sharepoint site in my browser.
Here’s the tail end of the debug message:
2011-11-17 15:05:47.830400 soap_transport_http: setCurlOption option=10015, value=
string(515) “[OMITED]”
2011-11-17 15:05:47.830528 soap_transport_http: set cURL POST data
2011-11-17 15:05:47.830632 soap_transport_http: setCurlOption option=10005, value=
string(17) “[user:pswd]”
2011-11-17 15:05:47.830753 soap_transport_http: set cURL payload
2011-11-17 15:05:47.830862 soap_transport_http: send and receive with cURL
2011-11-17 15:05:47.862661 soap_transport_http: No cURL error, closing cURL
2011-11-17 15:05:47.865537 soap_transport_http: Found HTTP header to skip
2011-11-17 15:05:47.865834 soap_transport_http: found proper separation of headers and document
2011-11-17 15:05:47.865956 soap_transport_http: cleaned data, stringlen: 0
2011-11-17 15:05:47.866173 soap_transport_http: found cookie: BIGipServerSP10STG_Pool = 1896943788.20480.0000
2011-11-17 15:05:47.866306 soap_transport_http: Got 401 Unauthorized with WWW-Authenticate: NTLM
2011-11-17 15:05:47.866413 soap_transport_http: HTTP authentication failed
2011-11-17 15:05:47.866528 soap_transport_http: end of send()
2011-11-17 15:05:47.867950 nusoap_client: Setting new cookie(s)
2011-11-17 15:05:47.868119 nusoap_client: Error: HTTP Error: HTTP authentication failed
Can anyone please post a simple step-by-step solution?
Many thanks in advance!
In the first instance, does you username require a domain to be specified, i.e. mydomain\username in order to log into the site…?
AL
Thanks Al. I had tried adding the domain in the original test, which failed. After some time off this problem, we just now found the problem. Yes, it does require the domain, but the problem was that getting the WSDL (which was on a different server) required authentication without the domain prefix. And my script used the same login details for both. Fixed now.
Hi,
Thanks for putting this post together.
I’m using nuSOAP but having difficulty connecting to sharepoint. I get:
soap_transport_http: Couldn’t open socket connection to server http://servername/_vti_bin/Lists.asmx, Error (-1218970084):
IT tell me the server is open for all communications so it shouldn’t be a firewall issue.
I’ve enabled basic authentication in IIS and I’m using the same login details as I use on the Sharepoint website.
Where am I going wrong?
Chris
I forgot to mention that I’m using my normal AD login details
Think I’ve cracked it now.
However, if I retreive a list from a site collection, I get “There is no Web named “/sites/collection”.
I can only seem to retreive from the top level site. I’ve changed the two location references in Lists.wsdl from http://domain/_vti_bin/Lists.asmx to http://domain/sites/collection/_vti_bin/Lists.asmx and tried using both the GUID and list name, but the error remains.
There’s lots out there when searching for the “There is no Web named” error in Google, but I can’t seem to the ‘the’ answer. Neither can I find a reason for the error.
Can anyone help?
Just wanted to drop a note that I was also having a 401 error and adding the domain to my username fixed it. This code will fetch a SharePoint list and output the result.
$usr = ‘DOMAIN\user’;
$pwd = ‘password’;
//URL to fetch
$url = “https://sharepoint/sites/subsite/List/_layouts/listfeed.aspx?List=GUID”;
//Initialize a cURL session
$curl = curl_init();
//Return the transfer as a string of the return value of curl_exec() instead of outputting it out directly
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//Set URL to fetch
curl_setopt($curl, CURLOPT_URL, $url);
//Force HTTP version 1.1
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
//Use NTLM for HTTP authentication
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
//Username:password to use for the connection
curl_setopt($curl, CURLOPT_USERPWD, $usr . ‘:’ . $pwd);
//Stop cURL from verifying the peer’s certification
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//Execute cURL session
$result = curl_exec($curl);
//Close cURL session
curl_close($curl);
echo “Result is ” . $result;
While this example is very helpful, I had the same problem that one of the commentors had regarding Office 365 Sharpoint online. I found an example of a slightly different type of authentication at http://macfoo.wordpress.com/2011/07/05/adding-items-to-a-sharepoint-list-using-php/.
I don’t know if David or anyone else has had success connecting to Office 365′s sharepoint online services recently, but based on the aforementioned link’s suggestion I have been trying to connect to the Authentication.asmx?WSDL (I even copied it locally as done with the List.wsdl here, with no success).
When I attempt to connect the SOAP response to the Login is “PASSWORNOMATCH”. Which sounds like a simple problem, but I am using the site owners credentials (triple checked). I am currently in contact with a Microsoft technician, but I fear that since I am connecting through PHP that they will not be able to help very much. I have read information that suggests that setting up the Single Sign On feature may help, but from the looks of it, this would require a windows server which I do not have. Any suggestions for possible Sharepoint site features to enable or security policies to modify?
I would love to hear about any php connection to sharepoint online (office 365) using a soap client.
Thanks,
Tyler
Tyler, I am currently in your situation, any luck?
Bjake, No … I am not having any luck. While I am not convinced that it is impossible to connect to the sharepoint Office 365 services with php, it does seem unlikley. I read this article —
http://blog.bugrapostaci.com/2011/07/05/sharepoint-2010-basic-authentication-and-php-net-web-service-connection/
Which seems to say that you need to be able to change the authorization requirements of the server, which cannot be done for the online services.
Not that it is much help, but I did have a chance to use my code with Sharpoint 2007 ( a local install ) and my code did query the sharepoint data successfully (which used a similar but not identical technique as above ), which at least made me feel like I wasn’t going crazy.
One last note. While I have not done this yet, and it does not provide me with what I could call a full solution … one thought to get PHP to read/write sharepoint data might be through an external database. Using the sharepoint BCS (Business data Connectivity Services ), I believe it may be possible to create a external data source that is MySQL database/table and have a list use that external table as its source. Although that might get ugly.
To download documents (pdf) from a document library http://www.strickspage.com/blog/displaying-and-downloading-sharepoint-document-libraries-using-php/
To download documents (pdf) from document library http://www.strickspage.com/blog/displaying-and-downloading-sharepoint-document-libraries-using-php/
Does camelot work for sharepoint online Office 365 edition?
We are trying to connect via PHP to a o365 sharepoint site too and without any luck! Can somebody help? Has somebody found a workaround? greets from Switzerland
Here is some information on how to get Authentication to Sharepoint online (Office 365 Edition).
http://community.office365.com/en-us/f/153/p/20137/94344.aspx#94344
My question is still : How to get this done with PHP?
Somebody I talked to while I was doing my initial evaluation of connecting to sharepoint from php recently posted http://macfoo.wordpress.com/2012/06/23/how-to-log-into-office365-or-sharepoint-online-using-php/
I have not tested it yet, but it seem pretty promising in resolving at least my issues, I hope this may help you too.
I use this to login ntlm
$soap->setCredentials($user, $pass, ‘ntlm’);
try{
$rawXMLresponse = $soapClient->GetListItems($
params)->GetListItemsResult->any;
catch(SoapFault $fault){
echo ‘Fault code: ‘.$fault->faultcode;
echo ‘Fault string: ‘.$fault->faultstring;
}
echo ‘
‘;
?>
But it is giving error: Fault code: HTTPFault string: Not Found
David,
I’m getting a 403 Forbidden. Any ideas?
Same here. How to solve this?
My mission was to connect to sharepoint.com, and as it turns out, it isn’t allowed.
Quality posts is the important to be a focus for the viewers to
visit the site, that’s what this web page is providing.
i am encountering ‘Fault code: HTTPFault string: Unauthorized’. Are there other solutions aside from enabling basic authentication? i am not the sharepoint admin.
Hi i’m trying to use the code via ntlm authentification but i’m still facing to connect :
HTTP/1.1 401 Unauthorized
Content-Length: 1656
Content-Type: text/html
Server: Microsoft-IIS/6.0
WWW-Authenticate: NTLM
MicrosoftSharePointTeamServices: 12.0.0.6219
X-Powered-By: ASP.NET
Date: Fri, 03 May 2013 09:42:50 GMT
my PHP code is :
…
$client = new nusoap_client($wsdl, true);
$client->setCredentials($username, $password, ‘NTLM’);
$client->setUseCurl(true);
$client->useHTTPPersistentConnection();
$client->setCurlOption(CURLOPT_USERPWD, $username.’:’.$password);
$client->soap_defencoding=’UTF-8′;
…