Solved

can't work with a json returned string

Posted on 2013-11-09
16
425 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
ID: 39636003
That is not valid JSON
0
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 500 total points
ID: 39636004
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
ID: 39636129
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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 

Author Comment

by:Johnny
ID: 39636130
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
ID: 39636146
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
ID: 39636149
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
ID: 39636152
<?
//****************************************************************
// 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
ID: 39636157
could you also please post the json string because it could be slightly different than the unserialized php string I have now.
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 39636170
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
ID: 39636176
[{"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
ID: 39636187
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
ID: 39636190

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
ID: 39636195
$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
ID: 39636196
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
ID: 39636201
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
ID: 39636210
Thank so much
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to send multiple emails at the same time in PHP 12 62
hasing a url 16 29
AWS EC2 & RDS Instance 5 37
PHP Installer 5 28
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.  …
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

825 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