Code Examples

PHP Code Examples

Here are some code examples for connecting to the Trellian Direct Search Network API via PHP. Be sure to replace user and pass with your Trellian Direct Search Network username and password, respectively and key with your API key.

Note: The below code examples have been tested in PHP 5 only. For compatibility with other PHP versions, some modifications may be required.

Add Keyword Example

This code example will a create a new Keyword Campaign, using the API function add_keyword.

<?php

// define credentials
$username = "user";
$password = "pass";
$api_key = "key";


#
# Create a new Keyword Campaign, using API function add_keyword
#


// define new campaign settings
$keyword = "credit cards"; // keyword to add
$max_bid = "5.00"; // maximum bid ($5)
$daily_limit = "200.00"; // daily spend limit ($200)
$negative = "interest free"; // negative keywords
$target = "https://www.trellian.com"; // target URL, including http://


// create query URL, correctly URL encoded -- It is best to urlencode all values, just in case
$query_url = "https://bid.trellian.com/api.html?username=" . urlencode($username) . "&password=" .urlencode($password) .
        "&api_key=" . urlencode($api_key) . "&mode=add_keyword&keyword=" . urlencode($keyword) .
        "&max_bid=". urlencode($max_bid) . "&daily_limit=" . urlencode($daily_limit) . "&negative=" .urlencode($negative) .
        "&target_url=" . urlencode($target);

// attempt connection and to put response into variable $res
$res = file_get_contents($query_url);

// if connection was successful
if($res) {

   // parse XML results

   // put response in XML object $results
   $results = simplexml_load_string($res); // you could also use a regex to get data, but this way is neater

   // check for error
   if($results->error) {

      // if there was an error, get reason reason and display
      $error_attributes = $results->error->attributes();

      // display error
      echo "Error: " . $error_attributes->error;

   } elseif($results->result) { // if there was NOT an error

      // check that status is Success

      $result_attributes = $results->result->attributes();

      if($result_attributes->Status == "Success"){

        // Success!
        echo "Successfully created Keyword Campaign: . $keyword;

      } else {

        // there was an error, show it

        // display error
        echo "Error status: " . $error_attributes->Status;

      }

   }


} else { // if there was a connection error

   // print error
   echo "Connection error!";

}

?>