last day (14 days later) » 

12:35 PM
1
Q: Parse JSON response in PHP - Protected keys?

MikeFI am using Curl to perform a GET request on a Sage server. The response is in JSON format, but I am unable to access the key/values. An example of the response is below: { "$descriptor": "Sage Accounts 50 | tradingAccount.", "$totalResults": 1508, "$startIndex": 1, "$itemsPerPage": 1508, ...

 
$resources is an array, not an object, because it starts with [
 
@SverriM.Olsen please see my edit
 
@SverriM.Olsen you're right, he must use json_decode
@MikeF var_dump($result); and post result
 
@SverriM.Olsen - please see my latest edits which have the full script and also the var_dump($result); output
 
@MikeF we need the dump after using json_decode(curl_exec($ch))
 
12:35 PM
@Peter the output of var_dump(json_decode(curl_exec($ch))); is null
 
@MikeF then it seems that the Sage response is not a valid json string. Use this online parser to check if the string is a valid json string JSON Parser
 
@Peter I've just copied the json response to jsonlint.com and it's saying it is valid JSON
 
@MikeF could you post the entire json? Maybe it's a recursion depth problem.
 
Hi Peter, Had to move to chat
The JSON response is too big to post on here. I shall pastebin it.
 
Ok
 
12:39 PM
Sorry, it's taking some time. There is 155,000 rows.
 
Just for testing. The json_decode function of PHP accepts a third parameter called $depth (default value 512). Try to increase this value and test if it works. json_decode(curl_exec($ch), false, 1024); // 1024 or bigger...
 
Hi, have you tried the approach I suggested or there's another issue after that?
 
Hi Alex, I receive the following: Notice: Trying to get property of non-object
Peter, I have put it to 1024 and still the same problem
 
Ok Mike, I'll wait fot the pastebin.
 
I can't get it on PB, it's too large
 
12:44 PM
gzip the file and upload it somewhere, i'm curious also :)
 
I've just uploaded it to my website
It's only small once in a txt file
 
got it
 
It's most frustrating to say the least!
 
The JSON string contains multiple single quotes. This maybe the problem. Test: json_decode(htmlentities(curl_exec($ch), ENT_QUOTES));
 
do you mind if I give you a not so "proper" solution ?
 
12:54 PM
Yes, of course. The only reason I need to be able to access this data is to get the $uuid to insert into a MySQL table.
 
<?php

$json_data = file_get_contents('sage-curl.txt');

$object = json_decode($json_data, true);

foreach ($object as $key => $value)
if (is_array($value))
foreach($value as $k=>$arr){
print $arr['$uuid'] . PHP_EOL;
print $arr['reference'] . PHP_EOL;
}
this will work
it's kinda hacky, since we're assuming that only the "resources" property is an array
but it seems to work
it runs in about 1 sec on my laptop
 
Peter, that has made no difference I'm afraid. I still receive the "Trying to get property of non-object" error on a foreach loop
Alex, I'll give that a try now and see how it runs
 
the "true" param, will take care of the "property of non-obj" since it will create an associative array instead of an object
 
It's curious. I've stored your sage-curl.txt as a json file, then file_get_content() over it and I used the json_decode() over the result and it works ok.
 
This is very strange
No matter what method I use, I am getting errors on everything
I'm going to try it using file_get_contents and a local sage-curl.txt file
Alex, that script didn't work using $ch in place of the json file
 
1:02 PM
let me try getting the text file with curl
getting the text file from your website with curl, json_decode, works fine
what errors are you getting?
 
When I try to perform a foreach on the $result, I am receiving the "property of non-object" error
Would it be a bad thing if I allowed you access to the raw data, so you can perform a curl on it?
 
it wouldn't be bad for me, i don't know on your end though :)
you can make the room private and change other settings
or something ... to make sure no one else gets to see it, i guess
 
1:17 PM
I'm not sure how I'd make it private
 
right hand side of screen, info button, then go to access
change from public to private
 
Ah I can't
That's only for moderators
It's ok, give me 10 minutes and I'll give you access. Then I'll close it down.
 
remove it
 
That is the URL to the data
Ok, removed
Now I need to give you the authorization header
 
remove it
 
1:22 PM
Ok, they've now gone
 
also edit this out from your question
give me 5 min to finish my smoke and i'll get on it :)
 
Perfect, it's really frustrating me. Strange how it works with a text file using file_get_contents(), but not on the raw data via curl
 
just one question before i start, do you need to do this on an ongoing basis or just one-time?
 
It'll be a script that is ran whenever a new customer is added to their Sage database.
Though it's fine doing a complete update of all records. I'm just going to be grabbing the $uuid and reference values, putting them into an array() and then inserting them into a MySQL table
 
Hi guys, I'm back.
 
1:30 PM
hey
 
Hi Peter
Would you like access to the raw data, to trial it?
 
I'm using your previous txt. I'm trying to retrieve data from the URL you posted on the originar thread.
 
Ah ok, I don't think you'll get anything from that. It's a local URL
Copy that one
 
Ok :)
 
and I'll remove
 
1:34 PM
Got it
 
Perfect :)
 
I have no response from that URL
 
Are you using the Authorization header?
$url = "http://92.233.229.129:5493/sdata/accounts50/GCRM/-/tradingAccounts?format=json&count=10";

$header = array();
$header[] = 'Authorization: Basic bWFuYWdlcjpjYmwyMDA4';
$header[] = 'Content-Type: application/json;';
 
I'm using your example
 
That's strange. Alex, can you access it?
 
1:38 PM
$header = array();
$header[] = 'Authorization: Basic bWFuYWdlcjpjYmwyMDA4';
$header[] = 'Content-Type: application/json;';

// Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Set the header
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
// Execute
$result = curl_exec($ch);

var_dump($result); // return NULL
 
$url = "http://92.233.229.129:5493/sdata/accounts50/GCRM/-/tradingAccounts?format=json&count=10";

$header = array();
$header[] = 'Authorization: Basic bWFuYWdlcjpjYmwyMDA4';
$header[] = 'Content-Type: application/json;';

// Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Set the header
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
// Execute
$result = curl_exec($ch);
That's the entire curl request I have at the moment
Which is pulling the data fine
Can you access the url in a browser, should ask for a username/password
 
Yeah, browser ask for user & password but your last example returns NULL
 
<?php
header('content-type:application/json');
//header('Content-Type: text/html; charset=utf-8');
error_reporting(E_ALL);

$url = "http://92.233.229.129:5493/sdata/accounts50/GCRM/-/tradingAccounts?format=json&count=10";

$header = array();
$header[] = 'Authorization: Basic bWFuYWdlcjpjYmwyMDA4';
$header[] = 'Content-Type: application/json;';

// Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
Gives me a complete JSON output
 
Ok finally worked. I'll do some test. Thanks.
 
Thanks Peter. I'm pulling my hair out here.
I'm just trying a few different methods and one of them is returning this as a value for all fields: 
 
1:56 PM
Please, check if the script which serves the JSON is encoded correctly. UTF-8 and not UTF-8 with BOM.
 
Do you mean the Sage server?
 
Yeah the problem is that this encoding puts 3 bytes ant the beginning of the string. I tried this and it worked ok:
var_dump(json_decode(substr($result, 3))); // First remove the 3 first characters of the string and then I decode.
 
ah, Peter, you beat me to it :)
 
Right, I undersand now. So it appears that the Sage server is returning UTF8 with BOM
 
here goes mine, all else stays the same
$string = curl_exec($ch);

$object = json_decode(remove_utf8_bom($string),true);


foreach ($object as $key => $value)
if (is_array($value))
foreach($value as $k=>$arr){
print $arr['$uuid'] . PHP_EOL;
print $arr['reference'] . PHP_EOL;
}

function remove_utf8_bom($text)
{
$bom = pack('H*','EFBBBF');
$text = preg_replace("/^$bom/", '', $text);
return $text;
}
 
2:00 PM
Which, unfortunately, I won't be able to change as it's a compiled application
 
that's ok, just use a utility function to remove the BOM, then json_decode
 
Wow, Alex!
You sir, are a genius
 
Can I post it as a solution?
 
Well, both of you are!
 
it was working ok when the rest of us were trying, cause we were simply copy pasting
yes sure, go ahead
 
2:01 PM
I saved the file as UTF-8 without BOM
So that'll probably explain it
So the 3 special characters that were preceding each value were a BOM, yes?
 
not preceding each value, at the start of the file
i think :)
 
Yes, it's a the start of the file.
 
Ah ok
and that's what was throwing the json_decode off
$out = array();
$i = 0;
foreach ($object as $key => $value)
if (is_array($value))
foreach($value as $k=>$arr){
$out[$i]['uuid'] = $arr['$uuid'] . PHP_EOL;
$out[$i]['ref'] = $arr['reference'] . PHP_EOL;
$i++;
}
print_r($out);
Just made a little change to the output, ready for the insert into the database.
Ah, is there an option to 'buy you a coffee' on here?
 
this is good to use, php.net/manual/en/function.json-last-error.php after using json_decode
 
Hahahahah
 
2:05 PM
it was always returning syntax error
 
Because of the BOM?
 
nah, but thanks for thinking about it :)
 
Why would it affect it, if it is at the start of the file though?
 
I've just posted the solution, please rate positive and mark as the solution.
 
yes, and the linter wasn't complaining about it, cause of copy paste
 
2:06 PM
Aahh
Simple things
5 hours I've been racking my brain over this
 
Fucking encoding!hahaha
 
:)
I seriously owe you both a drink! You have helped me no end.
 
The magic of stackoverflow!
Well guys, it's been a pleasure, see u!
 
Thanks Peter and Thanks Alex. Until the next time we meet!
 
it's been a fun challenge, cya around
 

last day (14 days later) »