Adding items to a Sharepoint list using PHP

*** UPDATE***

I have had a couple of people asking about using this with Sharepoint Online. For an example of how do that visit this post.

At work I was asked to populate a sharepoint list from a database report. I did a lot of searching on the web for how to’s, they all seemed a little old, but they did head me in the right direction. This is my adventure.

First thing is to get the log into the sharepoint using soap, I used my own class which extends the Zend_Soap_Client class. The most important thing to remember is that after successfully logging in you have to save the cookie to send on subsequent requests. Also remember to set the WSDL to the sharepoint list URL. Below is the code:

/**
 * Log into the sharepoint site
 * @param int $count How many times the function has been called
 * @return Cisc\Web\Soapclient
 */
function webserviceLogin($count=0)
{
    // Create soap client
    $wsdl = 'https://path/to/sharepoint/list/_vti_bin/Authentication.asmx?WSDL';
    $ws = new Cisc\Web\Soapclient($wsdl);
    $login = array('username'=>'user',
                   'password'=>'pass');
    try {
        $rs = $ws->Login($login);
        if($rs->LoginResult->ErrorCode != 'NoError'){
            throw new Exception($rs->LoginResult->ErrorCode);
        }
        $ws->setSoapCookieInfo($rs->LoginResult->CookieName, getCookieValue($ws->getLastResponseHeaders()));
        return $ws;
    } catch (SoapFault $ex) {
        $log = Zend_Registry::get('log');
        $log->err($ex->getMessage());
        sleep(20); // Sleep for 10 seconds and try again
        $count++;
        if ($count < 10) {
            return webserviceLogin($count);
        }
        scriptExit('Unable to process soap call!');
    }
}

Notice the getCookieValue function, this is used to extract the cookie value since sharepoint sends the name on success but not the value. The function parses the HTTP header and extracts the cookie value. The code is below:

/**
 * Get the cookie value from the http header
 *
 * @param string $header
 * @return string
 */
function getCookieValue($header)
{
    $header_array = explode("\r\n",$header);
    foreach($header_array as $header) {
        $loop = explode(":",$header);
        if($loop[0] == 'Set-Cookie') {
            $value = explode(".ASPXAUTH=",$loop[1]);
        }
    }
    return $value[1];
}

The next bit of oddity is creating the XML file to upload. The variable used to hold the new items is called any. Gotta love Microsoft.

/**
 * Generate the xml to populate the lists
 *
 * @param array $data
 * @return string
 */
function generateXml($data)
{
    $id = 1;
    foreach($data as $rowData) {
        $xml_batch .= "<Method Cmd='New' ID='$id'>
                        <Field Name='Title'>{$row['title']}</Field>
                     </Method>";
        $id++;// Increase id number
    }

    $listname = 'list';
    $xml_add = "<Batch ListVersion='1' OnError='Continue'>$xml_batch</Batch>";
    $xml = array(
            'listName' => $listname,
            'updates' => array('any' => $xml_add)
          );
    return $xml;
}

The next thing to do is update the list with the new items.

/**
 * Update the list with the data
 *
 * @param object $ws
 * @param array $params
 */
function updateList($ws,$params)
{
    $wsdl_list = 'https://paht/to/sharepoint/list/_vti_bin/Lists.asmx?WSDL';
    // Change wsdl file
    $ws->setWsdl($wsdl_list);
    try {
        // Need to send cookie for each request
        $ws->sendCookie();
        $rs = $ws->UpdateListItems($params);
    } catch (Exception $ex) {
        $log = Zend_Registry::get('log');
        $log->err($ex->getMessage());
        scriptExit('Unable to update the list: ' . $ex->getMessage());
    }
    return $rs->UpdateListItemsResult->any;
}

And that’s pretty much it. It’s simple once you figure out the oddities but maddening until you do.

Please leave any questions, comments or criticisms.

Advertisements

3 thoughts on “Adding items to a Sharepoint list using PHP

  1. Great example! Depending on the user’s experience of SharePoint webservices and the complexity of the application, building correct CAML queries and dealing with data conversion can be a little tricky (in any language). There is a framework available for querying SharePoint in php called Camelot PHP Tools, that let you query SharePoint using standard SQL syntax. It is built on a product called Camelot .NET Connector, that is kind of a “sharepoint sql driver” for .NET. For example:

    require_once ‘classes/class.camelot.soap.php’;

    $SharePointQuery = new SharePointQuery(
    array(
    ‘sql’ => “SELECT * FROM `shared documents` WHERE created > ‘2011-01-01′”,
    ‘compression’ => true,
    ‘connString’ => ‘sharepoint_connection’,
    ‘sharedKey’ => constant(“WSDL_SHARED_KEY”)
    )
    );

    print_r($SharePointQuery);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s