I'm using the Class "mysql2json" to make my Json.
<?php
class mysql2json{
static public function getJSON($resultSet,$affectedRecords){
mb_internal_encoding("UTF-8");
$numberRows=0;
$arrfieldName=array();
$i=0;
$json="";
//print("Test");
while ($i < mysql_num_fields($resultSet)) {
$meta = mysql_fetch_field($resultSet, $i);
if (!$meta) {
}else{
$arrfieldName[$i]=$meta->name;
}
$i++;
}
$i=0;
$json="{\n\"data\": [\n";
while($row=mysql_fetch_array($resultSet, MYSQL_NUM)) {
$i++;
//print("Ind ".$i."-$affectedRecords<br>");
$json.="{\n";
for($r=0;$r < count($arrfieldName);$r++) {
$json.="\"$arrfieldName[$r]\" : \"$row[$r]\"";
if($r < count($arrfieldName)-1){
$json.=",\n";
}else{
$json.="\n";
}
}
if($i!=$affectedRecords){
$json.="\n},\n";
}else{
$json.="\n}\n";
}
}
$json.="]\n};";
return $json;
}
}
?>
The problem is I'm getting a not valid JSON error in Xcode (iPhone App) and the JSON validator is saying there is an error on line 11 of the results even though line 11 is blank.
Validator: http://jsonlint.com/
Here is a sample URL.
http://leafseed.com/webservice.php?upc=1116102338
Xcode Error:
2012-01-11 08:55:46.137 GroceryVine[6476:bf03] -JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=10 \"Garbage after JSON\" UserInfo=0x9bbabc0 {NSLocalizedDescription=Garbage after JSON}
Validator Error
Parse error on line 11:
...." } ]};
--------------------^
Expecting 'EOF', '}', ',', ']'
Any Ideas?
Best Solution
I wouldn't bother with this class. Just use the native json_encode() DOCs PHP function as it will give you correctly formatted JSON very easily every time.
For example:
$json_arr = array();
while($row = mysql_fetch_array($resultSet, MYSQL_NUM)) {
$json_arr[] = $row;
}
echo json_encode($json_arr);
A list of other PHP JSON implementations can be found on the json.org website (hint: scroll down).
Direct answer
Looking at your updated question with debug output. Looks like there is an errant semi-colon (;) in your output.
Change your last append from
$json.="]\n};";
to
$json.="]\n}";
And I think that will fix your issue.
what about json_encode function and fetch data separately ?
http://php.net/manual/en/function.json-encode.php
The ; after the last curly brace is wrong
Replacing:
}
$json.="]\n};";
return $json;
}
With
}
$json.="]\n}";
return $json;
}
should solve your problem.
Related
I have the following code:
<?php
$json = file_get_contents("https://api.nanopool.org/v1/eth/payments/0x218494b2284a5f165ff30d097d3d7a542ff0023B");
$decode = json_decode($json,true);
foreach($decode['data'] as $val){
echo date('Y-m-d',$val['date']).' -- '.$val['amount'].' -- '.$val['txHash'].' -- '.$val['confirmed'];
echo "<br/>";
}
The API used (nanopool) being extremely unreliable, I get a non empty json (success) every 2 to 10 calls.
I tried to loop the file_get_contents (do... while) until getting a non empty json without success. What can you recommend to loop until I get an answer?
Maybe you can try something like this, still I don't recommend using this within a synchronous script (eg a web page) because you can't control the time needed to get a successfull answer.
<?php
function getFileFTW($url)
{
$fuse = 10;//maximum attempts
$pause = 1;//time between 2 attempts
do {
if($fuse < 10)
sleep($pause);
$s = #file_get_contents($url);
}
while($s===false && $fuse--);
return $s;
}
$json = getFileFTW("https://api.nanopool.org/v1/eth/payments/0x218494b2284a5f165ff30d097d3d7a542ff0023B");
if($json) {
$decode = json_decode($json,true);
//...
}
else {
//json not loaded : handle error
}
Is there anybody who knows how to get whole LDAP error codes?
I'm using in PHP ldap_error($ldapConn) for code and ldap_errno($ldapConn) for name of the error. But error 49 - LDAP_INVALID_CREDENTIALS has 'suberrors' like 49/525, 49/530 etc. I need whole number of error but ldap_error() shows only 49 for example.
You can do something like this:
ldap_get_option($ldapConn, LDAP_OPT_ERROR_STRING, $diagnosticMsg);
echo $diagnosticMsg;
Where $diagnosticMsg is then the full message that contains the extra information you're looking for.
In newer versions of PHP you can use LDAP_OPT_DIAGNOSTIC_MESSAGE instead. That will contain the extended error code you're looking for. You can parse it doing something like this:
function getExtendedErrorNumber($diagnosticMsg) {
$errorNumber = 0;
if (!empty($diagnosticMsg)) {
$errorNumber = explode(',', $diagnosticMsg);
if (!isset($errorNumber[2])) {
return 0;
};
$errorNumber = explode(' ', $errorNumber[2]);
if (!isset($errorNumber[2])) {
return 0;
};
$errorNumber = hexdec(intval($errorNumber[2]));
}
return $errorNumber;
}
Getting the PHP notice 'Notice: Trying to get property of non-object' from the following function that uses Google maps API to find the distance between two postcodes (specifically the 'return' line of the code is triggering the notice)
function findTheDistanceBetween($postcode_from, $postcode_to){
// tidy up spaces
$postcode_from = str_replace(" ", "+", $postcode_from);
$postcode_to = str_replace(" ", "+", $postcode_to);
// get JSON back from Google
$json = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode_from&destinations=$postcode_to&sensor=false&units=metric");
// convert to a normal array
$php_array = json_decode($json);
// extract output and return it
return $php_array->rows["0"]->elements["0"]->distance->value;
}
This is part of a drupal site if that makes any difference.
I am also getting another notice from the same return line:
Notice: Undefined offset: 0 in findTheDistanceBetween()
Any help much appreciated.
This might be a way to include error handling
$maps_object = json_decode($json);
if (isset($maps_object->status)) {
if ($maps_object->status == "OK") {
// extract output and return it
return $maps_object->rows[0]->elements[0]->distance->value;
} else {
// adapt content to your error handling
return 'json status: ' . $maps_object->status;
}
} else {
return 'could not obtain json';
}
How about replacing/surrounding the Noticed statement like this for your debug:
if (isset($maps_object->rows[0]->elements[0]->distance->value)) {
return $maps_object->rows[0]->elements[0]->distance->value;
} else {
$error = "Error in: ". __FUNCTION__ ."() file:". __FILE__ ." line:". __LINE__ ."<br>\njson: $json<br>\n";
echo $error;
return $error;
}
I'm trying to get this function to work but for some reason it errors out on the foreach line saying there is an invalid argument.
$scores= TESTAPI::GUL($user->ID);
if (empty($scores)) {
echo "<p>No Scores</p>";
} else {
foreach ($scores as $score) {
echo "<p>".$score."</p>";
}
}
The error I get is: PHP Warning: Invalid argument supplied for foreach()
Note: I need to keep the if... else... in the order it currently is.
Some variations for the if statement, prior to the for
if(!is_array($scores) && !count($scores) || empty($scores)){
if(!is_array($scores) && !count($scores)){
I can't use use var_dump($scores); because the error is on a page on a private website I run (can't provide links) and I am unable to find a way to recreate the error. Maybe someone knows a way I can capture data that causes the foreach to go wrong and save it to a log file?
You can use error_log in case it is no array:
$scores= TESTAPI::GUL($user->ID);
if (empty($scores)) {
echo "<p>No Scores</p>";
} else {
if(!is_array($scores)) {
$scores_info = print_r($scores, true);
error_log('$scores is no array but: ' . $scores_info);
echo "<p>No Scores</p>";
} else {
foreach ($scores as $score) {
echo "<p>".$score."</p>";
}
}
}
It will write to the error log. You can see more at the error_log doc how to configure it. You should clearly dry it up when you know what the error is, but for temporary catching it this works ...
Alright, I'm using the Blekko search API:
http://blekko.com/ws/?q=hello+%2Fjson
how would I go about parsing it ?
I have no experience of parsing JSON from PHP, so I'd appreciate a little help, and the json_decode() docs failed to explain everything for me, particularly getting the data inside RESULT. :) You know, [ and ].
Could you help pointing me in the right direction ? :)
Thank you, you're all so helpful! :)
Here's the code to access the API.
You should enter your own error/unexpected results handling where i've left the comments.
$data = file_get_contents('http://blekko.com/ws/?q=hello+%2Fjson');
if(!empty($data)){
$data = json_decode($data);
if(!empty($data->ERROR)){
// Error with API response.
} else {
$data = $data->RESULT;
if(empty($data)){
// No results.
} else {
// Uncomment the line below to see your data
// echo '<pre>' . print_r($data) . '</pre>';
foreach($data AS $key => $val){
echo $val->short_host . '<br />';
}
}
}
} else {
// Failed to retrieve data.
}