json from string to array using php - php

I have a problem with json parsing.
I have already read the many questions here on stackoverflow but I can't figured out what I'm missing.
In my site I use Facebook Api to post my feed using curl and it respond with a json message.
I take this response and I save it in my database.
In my Backoffice I need to retrieve this message and print it in case of error.
Here an example about an error message:
{"error":{"message":"(#1500) The url you supplied is invalid","type":"OAuthException","code":1500}}
In my php page I need to get just the message part so I did:
$message = get from the db and fetch;
$error_array = json_decode($message,true);
print_r($error_array);
but it doesn't print anything, just a blank page.
If I just print $message I can see the entire string.
What am I missing?
This issue it's driving me crazy all day long!!

I tried the following:
<pre>
<?php
$jsonStr = '{"error":{"message":"(#1500) The url you supplied is invalid","type":"OAuthException","code":1500}}';
$error_array = json_decode($jsonStr, true);
print_r($error_array);
?>
and getting output:
Array
(
[error] => Array
(
[message] => (#1500) The url you supplied is invalid
[type] => OAuthException
[code] => 1500
)
)
It's working as intended.
I suspect the problem is with this:
$message = get from the db and fetch;
After you load the $message variable, do a var_dump($message) and see if the string is in there (as expected).

$jsonString = '["m#gmail.com","b#gmail.com","c#gmail.com"]';
$arrayOfEmails=json_decode($jsonString);
Or
$jsonString = "[\"a#gmail.com\",\"b#gmail.com\",\"c#gmail.com\"]";
$arrayOfEmails=json_decode($jsonString);

Related

How to use Nominatim API through PHP to retrieve latitude and longitude?

Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// get the important data
$lati = $resp['lat'];
$longi = $resp['lon'];
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
return $data_arr;
}
The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:
[[DATE] America/New_York] PHP Notice: Undefined index: title in [...php] on line [...]
[[DATE] America/New_York] PHP Notice: Undefined variable: area in [...php] on line [...]
What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.
Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).
Would really appreciate any help with this, thank you!
Edit
This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.
The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.
// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
In full, with some abbreviation of the array building at the end for simplicity:
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return array($resp[0]['lat'], $resp[0]['lon']);
}
Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.

Warning: Illegal string offset 'code' in /path/ on line 17

I keep getting the error "Warning: Illegal string offset 'code' in /path/ on line 17". I have tried many things but don't know what the problem is. Here is my code:
require_once 'unirest-php-master/src/Unirest.php';
$response = Unirest\Request::post("https://andruxnet-random-famous-
quotes.p.mashape.com/?cat=movies",
array(
"X-Mashape-Key" => "key",
"Content-Type" => "application/x-www-form-urlencoded",
"Accept" => "application/json"
)
);
$encoded = json_encode($response,true);
echo $encoded['code'];
This code is being used to get information from the api and it is successfully getting the information but when I try to access an object in the array I get an error.
I have also tried to use json_decode instead of encode but that gives me an error about parameter 1 needing to be a string
Edit: line 17 is this line: echo $encoded['code'];
From your code, it seems like you want to print the response obtained from API (in JSON format). So, you should be doing json_decode here.
var_dump($response); // Check response obtained from API
$encoded = json_decode($response,true); // Change to json_decode
echo "<pre>"; print_r($encoded); // Debug decoded array
echo $encoded['code']; // Check data
I have resolved the issue. The first thing I did wrong was try to decode or encode it, I didn't need to do either. I was also using ["code"] rather than ->code

Problems manipulating JSON data in PHP

I'm not that handy with JSON so here goes. I'm receiving Amazon SNS notifications for bouncing email addresses to a listener (in PHP 5.5) which does:
$post = #file_get_contents("php://input");
$object = json_decode($post, true);
This gives me:
Type => Notification
MessageId => #####
TopicArn => #####
Message => {
"notificationType":"Bounce",
"bounce": {
"bounceSubType":"General",
"bounceType":"Permanent",
"bouncedRecipients":[{"status":"5.3.0","action":"failed","diagnosticCode":"smtp; 554 delivery error: dd This user doesn't have a yahoo.com account (testuser#yahoo.com) [0] - mta1217.mail.bf1.yahoo.com","emailAddress":"testuser#yahoo.com"}],
"reportingMTA":"dsn; ######",
"timestamp":"2014-10-27T16:37:42.136Z",
"feedbackId":"######"
},
"mail": {
"timestamp":"2014-10-27T16:37:40.000Z",
"source":"myemail#mydomain.com",
"messageId":"######",
"destination":["testuser#yahoo.com"]
}
}
I was expecting an associative array all the way down but instead it's an array only at the top level and with JSON strings inside. I've tried everything I can think of, including json_decoding further parts of the array, but I'm struggling to access the data in a simple way. What I need is the "destination" email address which should be in $object['Message']['mail']['destination'][0].
Can anyone point out what I'm doing wrong here? Thanks.
It looks like $object['Message'] is also json encoded. Perhaps because it's using some generic container format for service call results. Try this
$post = #file_get_contents("php://input");
$object = json_decode($post, true);
//Message contains a json string
$object['Message'] = json_decode($object['Message'], true);
//Then access the structure using array notation
echo $object['Message']['mail']['destination'][0];

Seem to be making valid JSONarray object but how to get php to process it?

I'm sending a string to a php script and trying to make a jsonarray out of it for processing and putting it into an sql table. I send a string from an android application to the server:
[{"name":"bob","datetime":"2012-04-14 10:40"},{"name":"Anonymous","datetime":"2012-04-14 10:40"}]
I used http://jsonlint.com/ to validate the jsonarray and it is valid. When I have the following php script:
<?php
$json_as = stripslashes($_POST["json_a"]);
//$out.=json_decode(jsoninfo);
$realjson = json_decode($json_as, true);
//print $json_as;
//echo $realjson[name];
//print $realjson[name];
print $json_as;
?>
I see get the following info in my LogCat:
The Response text is [{"name":"bob","datetime":"2012-04-14 10:40"},{"name":"Anonymous","datetime":"2012-04-14 10:40"}]
I've been trying to use this for reference without luck: http://webhole.net/2009/08/31/how-to-read-json-data-with-php/
But when I try to change the php script to pring something out from the variable $realjson, nothing comes back. How do I get the information out of the json string I am sending?
Here is complete tutorial to send and recieve JSON data between PHP and Android.
I hope this can help you.
Query:
http://localhost/testJson.php?data=[{%22name%22:%22bob%22,%22datetime%22:%222012--04-14%2010:40%22},{%22name%22:%22Anonymous%22,%22datetime%22:%222012-04-14%2010:40%22}]
PHP CODE :
COde :
<?php
$data = $_REQUEST['data'];
print_r(json_decode($data));
?>
Result :
Array ( [0] => stdClass Object ( [name] => bob [datetime] =>
2012--04-14 10:40 ) 1 => stdClass Object ( [name] => Anonymous
[datetime] => 2012-04-14 10:40 ) )
Sent a string in JSON format, then used the following code:
$json_as = stripslashes($_POST["json_a"]);
trim($json_as, "[");
trim($json_as, "]");
$realjson = json_decode($json_as, true);
//$uses = "name";
mysql_select_db("thoughtsdata",$con);
foreach($realjson as $item) {
$name = $item[name];
$datetime = $item[datetime];
//processed code
}

Why php's soapCall gives string conversion error?

// Set username and password
$ih_soap_user= $this->config->item('interUser');
$ih_soap_pass=$this->config->item('interPass');
//echo $ih_soap_user.':P:'.$ih_soap_pass;
// Set soap namespace
$ih_soap_ns = 'http://www.interhome.com/webservice';
// Create new instance of SoapClient with the interhome web service URL
$client = new
SoapClient($this->config->item('interSoap'),array('trace'=>'1'));
// Create new soap header and set username and password
$header = new SoapHeader($ih_soap_ns,
'ServiceAuthHeader',
array('Username' => $ih_soap_user,'Password' =>
$ih_soap_pass),
true
);
// Prepare p// Prepare parameters
$params = array('inputValue' =>array(
'Page'=>$page,
'PageSize'=>'10',
'OrderDirection'=>'Ascending',//Descending
'OrderBy'=>'Price',//Favorite,Place
'LanguageCode'=>'EN',
'CurrencyCode'=>'EUR',
'CountryCode'=>trim($ajaxSearchCountryCode),
'RegionCode'=>trim($ajaxSearchRegionCode),
'PlaceCode'=>$ajaxSearchPlaceCode,
'CheckIn'=> $ajaxSearchCheckinDate,
'Duration'=>'7',
'ThemeFilter'=>$ajaxSearchTheme,
'HouseApartmentType'=>array('House'=>'House'),
'SpecialOffer'=>'AnySpecialOffer',
'PaxMin'=>'1',
'PaxMax'=>'',
'RoomsMin'=>'1',
'RoomsMax'=>'',
) );
try{
$result = $client->__soapCall("Search",array('parameters'=> $params),null,$header);
Hi guys..Any Idea why this call when I pass any not empty array, as for example ,as I made for 'HouseApartmentType', returns this error
A PHP Error was encountered
Severity: Notice Message:
Array to string conversion
Filename:
controllers/houses.php Line
Number: 269
And when it's only empty array or a string the soap call function is working... I need to pass array of options to one parameter....
LINE 269 is
$result = $client->__soapCall("Search",array('parameters'=> $params),null,$header);
This is probably solved already, but I also had problems with this and I thought I should post here when I finally found the solution. (The solution is not nusoap, it throws the same error.)
The error only seems to come from the soapCall call generation, it really is the Web Service that causes it. When you run __soapCall, it first asks the server which datatypes the parameters should have and then tries to comply. So if you try to feed an array when the service expects a string, it will do the array to string conversion when the request is generated.
i think you should look at the manual how a soapcall work:
$params = array(
'Page'=>$page,
'PageSize'=>'10',
'OrderDirection'=>'Ascending',//Descending
'OrderBy'=>'Price',//Favorite,Place
'LanguageCode'=>'EN',
'CurrencyCode'=>'EUR',
'CountryCode'=>trim($ajaxSearchCountryCode),
'RegionCode'=>trim($ajaxSearchRegionCode),
'PlaceCode'=>$ajaxSearchPlaceCode,
'CheckIn'=> $ajaxSearchCheckinDate,
'Duration'=>'7',
'ThemeFilter'=>$ajaxSearchTheme,
'HouseApartmentType'=>'House', // changed to string instead of array
'SpecialOffer'=>'AnySpecialOffer',
'PaxMin'=>'1',
'PaxMax'=>'',
'RoomsMin'=>'1',
'RoomsMax'=>'' );
i simplified the array and you should test it and look if this is the kind of result you are looking for.
Also look for ordering errors like the example shown in php.net

Categories