views:

28

answers:

1

Hello, I'm getting a fatal PHP error when trying to execute my script: Using $this when not in object context The script collects data from Google Analytics via API, then displays it on a page.

Below is the piece of code where the script dies:

$records = $this->getAnalyticRecords ( date ( 'Y-m-d', $startTime ), date ( 'Y-m-d', $endEnd ), 'ga:date', 'ga:visitors,ga:newVisits,ga:visits,ga:pageviews,ga:timeOnPage,ga:bounces,ga:entrances,ga:exits' );

getAnalyticsRecords is set by:

function getAnalyticRecords($startDate, $endDate, $dimensions, $metrics, $sort = '', $maxResults = '') {

    $url = 'https://www.google.com/analytics/feeds/data';
    $url .= "?ids=" . $this->profile;
    $url .= "&start-date=" . $startDate;
    $url .= "&end-date=" . $endDate;
    $url .= "&dimensions=" . $dimensions;
    $url .= "&metrics=" . $metrics;
    if (! empty ( $sort )) {
        $url .= "&sort=" . $sort;
    }
    if (! empty ( $maxResults )) {
        $url .= "&max-results=" . $maxResults;
    }
    if (($feedData = $this->fetchFeed ( $url )) === FALSE) {
        return array ();
    }
    $doc = new DOMDocument ( );
    $doc->loadXML ( $feedData );
    $results = array ();

    $aggregates = $doc->getElementsByTagName ( 'aggregates' );
    foreach ( $aggregates as $aggregate ) {
        $metrics = $aggregate->getElementsByTagName ( 'metric' );
        foreach ( $metrics as $metric ) {
            $results ['aggregates'] ['metric'] [$metric->getAttribute ( 'name' )] = $metric->getAttribute ( 'value' );
        }
    }

    $entries = $doc->getElementsByTagName ( 'entry' );
    foreach ( $entries as $entry ) {
        $record = array ();
        $record ["title"] = $entry->getElementsByTagName ( 'title' )->item ( 0 )->nodeValue;
        $dimensions = $entry->getElementsByTagName ( 'dimension' );
        foreach ( $dimensions as $dimension ) {
            $record ['dimension'] [$dimension->getAttribute ( 'name' )] = $dimension->getAttribute ( 'value' );
        }
        $metrics = $entry->getElementsByTagName ( 'metric' );
        foreach ( $metrics as $metric ) {
            $record ['metric'] [$metric->getAttribute ( 'name' )] = $metric->getAttribute ( 'value' );
        }
        $results ['entry'] [] = $record;
    }
    return $results;
}
+2  A: 

You should listen to the error. You are using $this when not in a class.

Try either enclosing your code in a class or omitting $this->. Use global instead.

Borealid
Since the second code given is in a class, how do I reintroduce that class back? Possibly `$xfplugin = new googleAnalyticsPlugin;`
Shamil
@ct2k7 if getAnalyticRecords() is a method of a class called googleAnalyticsPlugin, then yes. `$xfplugin = new googleAnalyticsPlugin; $records = $xfplugin->getAnalyticRecords(...);`
timdev
Thanks timdiv and Borealid :)
Shamil