Solved

can't work with a json returned string

Posted on 2013-11-09
16
408 Views
Last Modified: 2013-11-09
i have a json string i'm capturing form piwik analytics, for page hit

heres the data
a:1:{i:0;a:18:{s:5:"label";s:27:"/single_event_page.php?id=2";s:9:"nb_visits";i:1;s:7:"nb_hits";i:1;s:14:"sum_time_spent";i:714;s:28:"nb_hits_with_time_generation";s:1:"1";s:19:"min_time_generation";d:0.409999999999999975575093458246556110680103302001953125;s:19:"max_time_generation";d:0.409999999999999975575093458246556110680103302001953125;s:15:"entry_nb_visits";s:1:"1";s:16:"entry_nb_actions";s:1:"2";s:22:"entry_sum_visit_length";s:3:"715";s:18:"entry_bounce_count";s:1:"0";s:26:"sum_daily_nb_uniq_visitors";i:1;s:32:"sum_daily_entry_nb_uniq_visitors";i:1;s:16:"avg_time_on_page";d:714;s:11:"bounce_rate";s:2:"0%";s:9:"exit_rate";s:2:"0%";s:19:"avg_time_generation";d:0.409999999999999975575093458246556110680103302001953125;s:3:"url";s:52:"http://completelocal.info/single_event_page.php?id=2";}}

Open in new window


i've tried varous way to try and use this info and everything i try either is blank or null as a return so what am i doing wrong
im trying to see how many unique hits are on the page

heres my code i have
<?
//****************************************************************
// Filename..: __.php
// Author....: __
// Date......: mm/dd/yyyy
// Purpose...: __
// SQL.......: server/database/tables/tablename
//****************************************************************
// include("filename.php");

function prettyPrint( $json )
{
    $result = '';
    $level = 0;
    $prev_char = '';
    $in_quotes = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );

    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if( $char === '"' && $prev_char != '\\' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
            switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;

                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;

                case ':':
                    $post = " ";
                    break;

                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
        $prev_char = $char;
    }

    return $result;
}

$id ="2";
$url = "http://xxxx.xxx/analytics/index.php?module=API&method=Actions.getPageUrl&pageUrl=/single_event_page.php?id=" . $id . "&idSite=1&period=month&date=today&format=php&filter_limit=1&token_auth=0a653dd77008f450c5ca2493f4e9046c";
echo "url info: ".$url;
$page_hits_info = file_get_contents($url);
$contents = file_get_contents($url); 
$contents = utf8_encode($contents); 
$results = json_decode($contents);
echo "<br>";
$json=$results;
var_dump(json_decode($json));
echo "<br>";
var_dump(json_decode($json, true));
/**/

echo "<br>";
echo "<pre>";
var_dump($json);
echo "</pre>";


echo "<br> new <br>";
$id ="2";
$url = "http://xxxx.xxx/analytics/index.php?module=API&method=Actions.getPageUrl&pageUrl=/single_event_page.php?id=" . $id . "&idSite=1&period=month&date=today&format=php&filter_limit=1&token_auth=0a653dd77008f450c5ca2493f4e9046c";

$json_string = $url;
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
echo "<pre>";
var_dump($obj);
echo "</pre>";



$json_data1='a:1:{i:0;a:18:{s:5:"label";s:27:"/single_event_page.php?id=2";s:9:"nb_visits";i:1;s:7:"nb_hits";i:1;s:14:"sum_time_spent";i:714;s:28:"nb_hits_with_time_generation";s:1:"1";s:19:"min_time_generation";d:0.409999999999999975575093458246556110680103302001953125;s:19:"max_time_generation";d:0.409999999999999975575093458246556110680103302001953125;s:15:"entry_nb_visits";s:1:"1";s:16:"entry_nb_actions";s:1:"2";s:22:"entry_sum_visit_length";s:3:"715";s:18:"entry_bounce_count";s:1:"0";s:26:"sum_daily_nb_uniq_visitors";i:1;s:32:"sum_daily_entry_nb_uniq_visitors";i:1;s:16:"avg_time_on_page";d:714;s:11:"bounce_rate";s:2:"0%";s:9:"exit_rate";s:2:"0%";s:19:"avg_time_generation";d:0.409999999999999975575093458246556110680103302001953125;s:3:"url";s:52:"http://xxxx.xxx/single_event_page.php?id=2";}';
$obj1 = json_decode($json_data1);
echo "<pre>";
var_dump($obj1);
echo "</pre>";


?>

Open in new window

note: i changed the domain name

thank you in advance for any code or help you may provide
0
Comment
Question by:Johnny
  • 8
  • 7
16 Comments
 
LVL 58

Expert Comment

by:Gary
Comment Utility
That is not valid JSON
0
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 500 total points
Comment Utility
That is not a json string.

One solution would be to change the requested format in your url, on line 87 change:
...&format=php&...

Open in new window

to
...&format=json&...

Open in new window

0
 
LVL 35

Expert Comment

by:Robert Schutt
Comment Utility
I just tested out the other option, if you want to work with the current format (php serialized string), use unserialize instead of json_decode.

I only tried out the literal string, which needed some changes near the end to work:
$json_data1='a:1:{i:0;a:18:{s:5:"label";s:27:"/single_event_page.php?id=2";s:9:"nb_visits";i:1;s:7:"nb_hits";i:1;s:14:"sum_time_spent";i:714;s:28:"nb_hits_with_time_generation";s:1:"1";s:19:"min_time_generation";d:0.409999999999999975575093458246556110680103302001953125;s:19:"max_time_generation";d:0.409999999999999975575093458246556110680103302001953125;s:15:"entry_nb_visits";s:1:"1";s:16:"entry_nb_actions";s:1:"2";s:22:"entry_sum_visit_length";s:3:"715";s:18:"entry_bounce_count";s:1:"0";s:26:"sum_daily_nb_uniq_visitors";i:1;s:32:"sum_daily_entry_nb_uniq_visitors";i:1;s:16:"avg_time_on_page";d:714;s:11:"bounce_rate";s:2:"0%";s:9:"exit_rate";s:2:"0%";s:19:"avg_time_generation";d:0.409999999999999975575093458246556110680103302001953125;s:3:"url";s:42:"http://xxxx.xxx/single_event_page.php?id=2";}}'; // note changed s:52 to s:42 and added }

$obj1 = unserialize($json_data1);

echo "<pre>";
var_dump($obj1);
echo "</pre>";

Open in new window

You can see that it works on my site here: http://schutt.nl/ee/Q_28289970/
0
 

Author Comment

by:Johnny
Comment Utility
i changed the output to json thanks for that
now how do i get the value please?
array(1) {
  [0]=>
  object(stdClass)#1 (18) {
    ["label"]=>
    string(27) "/single_event_page.php?id=2"
    ["nb_visits"]=>
    int(1)
    ["nb_hits"]=>
    int(1)
    ["sum_time_spent"]=>
    int(714)
    ["nb_hits_with_time_generation"]=>
    string(1) "1"
    ["min_time_generation"]=>
    float(0.41)
    ["max_time_generation"]=>
    float(0.41)
    ["entry_nb_visits"]=>
    string(1) "1"
    ["entry_nb_actions"]=>
    string(1) "2"
    ["entry_sum_visit_length"]=>
    string(3) "715"
    ["entry_bounce_count"]=>
    string(1) "0"
    ["sum_daily_nb_uniq_visitors"]=>
    int(1)
    ["sum_daily_entry_nb_uniq_visitors"]=>
    int(1)
    ["avg_time_on_page"]=>
    int(714)
    ["bounce_rate"]=>
    string(2) "0%"
    ["exit_rate"]=>
    string(2) "0%"
    ["avg_time_generation"]=>
    float(0.41)
    ["url"]=>
    string(52) "http://completelocal.info/single_event_page.php?id=2"
  }
}

Open in new window


echo "page hits: ".$page_hits['0']['nb_hits'];

Open in new window


does not seam to work
0
 

Author Comment

by:Johnny
Comment Utility
echo "page hits: ".$page_hits['0'];

Open in new window

returns


Catchable fatal error: Object of class stdClass could not be converted to string in /home/local/public_html/page_hits.php on line 80

so how do i get the nb hits please??
0
 
LVL 35

Expert Comment

by:Robert Schutt
Comment Utility
That can have a number of reasons, for starters there is no $page_hits variable in your original posted code so can you check that and if it's there now please show your current code?
0
 

Author Comment

by:Johnny
Comment Utility
<?
//****************************************************************
// Filename..: __.php
// Author....: __
// Date......: mm/dd/yyyy
// Purpose...: __
// SQL.......: server/database/tables/tablename
//****************************************************************
// include("filename.php");

function prettyPrint( $json )
{
    $result = '';
    $level = 0;
    $prev_char = '';
    $in_quotes = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );

    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if( $char === '"' && $prev_char != '\\' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
            switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;

                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;

                case ':':
                    $post = " ";
                    break;

                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
        $prev_char = $char;
    }

    return $result;
}

$id ="2";
$url = "http:/xxx.xxx/analytics/index.php?module=API&method=Actions.getPageUrl&pageUrl=/single_event_page.php?id=" . $id . "&idSite=1&period=month&date=today&format=json&filter_limit=1&token_auth=0a653dd77008f450c5ca2493f4e9046c";
echo "url info: ".$url;


$json_string = $url;
$jsondata = file_get_contents($json_string);
$page_hits = json_decode($jsondata);
echo "<pre>";
echo prettyPrint($jsondata);
echo "</pre>";
echo "<pre>";
var_dump($page_hits);
echo "</pre>";


echo "<pre>";
var_dump($page_hits['0']['stdClass']);
echo "</pre>";

echo "page hits: ".$page_hits['0']['stdClass']['nb_hits'];







?>

Open in new window

opps sorry forgot that part
0
 
LVL 35

Expert Comment

by:Robert Schutt
Comment Utility
could you also please post the json string because it could be slightly different than the unserialized php string I have now.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 35

Expert Comment

by:Robert Schutt
Comment Utility
As an aside, after unserializing the string you posted before, the following code works:
echo "nb_hits: ".$obj1[0]['nb_hits'];

Open in new window

0
 

Author Comment

by:Johnny
Comment Utility
[{"label":"\/single_event_page.php?id=2","nb_visits":1,"nb_hits":1,"sum_time_spent":714,"nb_hits_with_time_generation":"1","min_time_generation":0.41,"max_time_generation":0.41,"entry_nb_visits":"1","entry_nb_actions":"2","entry_sum_visit_length":"715","entry_bounce_count":"0","sum_daily_nb_uniq_visitors":1,"sum_daily_entry_nb_uniq_visitors":1,"avg_time_on_page":714,"bounce_rate":"0%","exit_rate":"0%","avg_time_generation":0.41,"url":"http:\/\/xxx.xxx\/single_event_page.php?id=2"}]

Open in new window

0
 
LVL 35

Expert Comment

by:Robert Schutt
Comment Utility
Ok, I'll have a look. In the mean time, another question...

Your posted code has an extra bit in it:
['stdClass']

Open in new window

Which is not present in the posts where you ask how to get to the info. Is that part of the problem?
0
 

Author Comment

by:Johnny
Comment Utility

Your posted code has an extra bit in it: ['stdClass']

no idea i get it if i var_dump it
0
 

Author Comment

by:Johnny
Comment Utility
$json_string = $url;
$jsondata = file_get_contents($json_string);
$page_hits = json_decode($jsondata);

echo "<pre>";
var_dump($page_hits);
echo "</pre>";

Open in new window

outputs
array(1) {
  [0]=>
  object(stdClass)#1 (18) {
    ["label"]=>
    string(27) "/single_event_page.php?id=2"
    ["nb_visits"]=>
    int(1)
    ["nb_hits"]=>
    int(1)
    ["sum_time_spent"]=>
    int(714)
    ["nb_hits_with_time_generation"]=>
    string(1) "1"
    ["min_time_generation"]=>
    float(0.41)
    ["max_time_generation"]=>
    float(0.41)
    ["entry_nb_visits"]=>
    string(1) "1"
    ["entry_nb_actions"]=>
    string(1) "2"
    ["entry_sum_visit_length"]=>
    string(3) "715"
    ["entry_bounce_count"]=>
    string(1) "0"
    ["sum_daily_nb_uniq_visitors"]=>
    int(1)
    ["sum_daily_entry_nb_uniq_visitors"]=>
    int(1)
    ["avg_time_on_page"]=>
    int(714)
    ["bounce_rate"]=>
    string(2) "0%"
    ["exit_rate"]=>
    string(2) "0%"
    ["avg_time_generation"]=>
    float(0.41)
    ["url"]=>
    string(52) "http://xxxxx/single_event_page.php?id=2"
  }
}

Open in new window

0
 
LVL 35

Assisted Solution

by:Robert Schutt
Robert Schutt earned 500 total points
Comment Utility
This seems to do the trick:
$obj = $page_hits[0];
echo "page hits: ".$obj->nb_hits;

Open in new window

0
 
LVL 35

Expert Comment

by:Robert Schutt
Comment Utility
quick check to loop over all items:
foreach ($page_hits[0] as $key => $val) {
    echo "$key: $val<br>";
}

Open in new window

You can see the output here: http://schutt.nl/ee/Q_28289970/index2.php
0
 

Author Closing Comment

by:Johnny
Comment Utility
Thank so much
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now