Could not convert json string to array using PHP - php

I need one help. I am unable to convert string to json array using PHP. I am explaining my code below.
$education=$_POST['education'];
the above line give this output [{'name':'aaa','id':'12'},{'name':'bbb','id':'20'}]. But its coming as a string .I tried to convert into array like below but it gived output as null
$edu=json_decode($education,true);
print_r($edu);
It gives the empty output. Here I need to convert it to array and populate all data. Please help me.

Hi You need to make your json string like below:
$arr = '[{"name":"aaa","id":"12"},{"name":"bbb","id":"20"}]';
$a = json_decode($arr);
echo "<pre>";
print_r($a);
die;
it will show your output like below:
Array
(
[0] => stdClass Object
(
[name] => aaa
[id] => 12
)
[1] => stdClass Object
(
[name] => bbb
[id] => 20
)
)

In php, you can use this function to check valid json:
function _isJsonString($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
You can also check online for valid json: http://json.parser.online.fr/
Hope this will help.

Related

Trying to extract value from Soap XML output

I'm using PHP SoapClient to call a SOAP service.
I'm using the following code to return the below view
$response = $client->Get($request);
echo '<pre>';
print_r($response);
echo '</pre>';
echo '<hr>';
Here's the response
stdClass Object
(
[TransactionID] => 17ACE7B75CB6SDBX
[ResponseType] => SYNC
[Parameters] => stdClass Object
(
[Param] => stdClass Object
(
[_] => SANDBOX20101001123321125.168.214.72125.168.253.29912003D60E04CC4C1F8
[id] => SessionLogRecord
)
)
)
Here is , showing the elements within it that I want to extract the values of
<onlinesessionrecord><serviceid>SANDBOX</serviceid><datetime>20101001123321</datetime><ipaddress>125.168.214.72</ipaddress><nasipaddress>125.168.253.2</nasipaddress><nasport>9912</nasport><sessionid>003D60E04CC4C1F8</sessionid></onlinesessionrecord>
For example, I am trying to extract from above
I have tried to display it using the following, but I get an error "Attempt to read property "onlinesessionrecord" on string"
$data = $response->Parameters->Param->_->onlinesessionrecord->ipaddress;
print_r($data);
If anyone knows what I'm doing wrong, your advice would be appreciated.
I am sure this is very simple, I just seem to struggle with xml.
--- Next Day, further findings after help from comments ---
So, thanks to the comments below, I have now go to this point. If I use the below:-
$data = simplexml_load_string($response->Parameters->Param->_);
$out = $data->IPAddress; // same if I do the following $data[0]->IPAddress;
print_r($out);
I get this:-
SimpleXMLElement Object ( [0] => 125.168.214.72 ) if I do the below.
But I just want to extract the IPAddress value and assign it to a variable. I have tried 2 ways
$out = $data->IPAddress;
and
$out = $data[0]->IPAddress;
Both give the same output, I just want to actual IPAddress and assign it to a variable.

How to get orderId from below array?

$receipt array give the below output. How to get orderId ?
pr($data); die;
to get orderId, $data['receipt']['orderId']; But its gives me error..
App\Model\Entity\PaymentDetail Object
(
[id] => 4
[user_id] => 4
[company_id] => 5
[receipt] => {"orderId":"GPA.3312-5688-8401-53436","packageName":"com.kenbar.mynus2","productId":"com.mynus2.subscription99","purchaseTime":1534914306517,"purchaseState":0,"purchaseToken":"gefffblagdakjleamfngklli.AO-J1Ow9Q5PncOoRk-oshlRBQ8kVqt3A4uIZuQi6InX7sr4bx2lNzjS-VjOXyMIwkl2G-afrI0fzoVLEADNZP2RWekoxwe4ko1M884JALYhaZsxo44U9DshbKJxbDNQHcCx9_z0yQpxc","autoRenewing":true}
)
$orderJson = json_decode(data['receipt'],true);
print_r($orderJson['orderId']);
As data['receipt'] contains a JSON string you need to parse it externally before consuming it as an object.
$orderId=json_decode($your_array->receipt);
echo $orderId->orderId;
You have a json as a string in your stdClass object field so you need to decode it first before you access it.
The above code will work for you.
You can use
$order_id = json_decode($data->reciept, true)["orderId"];

Convert PHP string to JSON array(key:value)

I have the following string that I receive from an API call:
a = "{
"option1"=>"Color",
"attribute1"=>{0=>"Black", 1=>"White",2=>"Blue"},
"option2"=>"Size",
"attribute2"=>{0=>"S", 1=>"L",2=>"M"}
}"
I would like to convert it to a JSON array; So, I have tried JSON_encode(), but it returns the following string:
""{\"option1\"=>\"Color\",\"attribute1\"=>{0=>\"Black\", 1=>\"White\",2=>\"Blue\"},\"option2\"=>\"Size\",\"attribute2\"=>{0=>\"S\", 1=>\"L\",2=>\"M\"}}""
Could you please advise me on how to achieve what i want.
Thanks
The preferable way would be affecting the service which gives you such kind of strings to get a valid JSON string(if it's possible). At the moment, if it's about adapting some "arbitrary" string to JSON notation format and further getting a JSON "array" use the following approach with preg_replace and json_decode functions:
$json_str = '{
"option1"=>"Color",
"attribute1"=>{0=>"Black", 1=>"White",2=>"Blue"},
"option2"=>"Size",
"attribute2"=>{0=>"S", 1=>"L",2=>"M"}
}';
// To get a 'pure' array
$arr = json_decode(preg_replace(["/\"?(\w+)\"?=>/", "/[\r\n]|\s{2,}/"], ['"$1":', ''], $json_str), true);
print_r($arr);
The output:
Array
(
[option1] => Color
[attribute1] => Array
(
[0] => Black
[1] => White
[2] => Blue
)
[option2] => Size
[attribute2] => Array
(
[0] => S
[1] => L
[2] => M
)
)
To get a JSON string representing an array:
$json_arr = json_encode($arr);
print_r($json_arr);
The output:
{"option1":"Color","attribute1":["Black","White","Blue"],"option2":"Size","attribute2":["S","L","M"]}

JSON decode in PHP from a url

Hello i am new with Json in php. I have a web service that gives me data in json format.
I take this data making decode put when i try to use this data i cant
Here is my code:
$url = "http://www.webinsurer.gr/....;
$json = json_decode(#file_get_contents($url), true);
and if i make debug i see the data i take :
[file] => C:\xampp\htdocs\development.insurancemarket.gr\mvc\protected\models\Ratingsmail.php
[line] => 18
[data] => Array
(
[0] => Array
(
[POL_EXPIREDATE] => 2014-05-19 12:00:00
[INCO_IWCODE] => 41
[INCO_DESC] => MAPFRE ASISTENCIA
[PACK_IWCODE] => 0
[PACK_DESC] =>
[OFFERCODE] =>
[PAYMENTCODE] =>
)
[1] => Array
(.....
But i dont now how to use that data. when i try this :
$b= $json->{1}->{'INCO_IWCODE'};
Debug::debuger($b);
the result is nothing
what is wrong? sorry for long post.
When setting the second argument on json_decode to true, you are actively asking for the data to be returned in an associative array and not objects. Thats why your code didn't work.
Demo
You are converting json to associative array. You need to use;
$b = $json["data"][1]["INCO_IWCODE"];
$a = $json[0]->INCO_IWCODE;
That worked for my guys. thanks you all!!!

PHP json_decode not working - displays NULL output

I'm trying to use JSON decode to retrieve some information but it's not working, it's just showing the data as null when I use var_dump
Here's the JSON formatted data passed in the URL
orderSummary={"orderInfo":[{"itemNumber":"1","quantity":"3","price":"5.99","productName":"Item_B"}]}
When I simply echo the un-decoded string I get the following
echo $_GET['orderSummary'];
//displays the following
{\"orderInfo\":[{\"itemNumber\":\"1\",\"quantity\":\"3\",\"price\":\"5.99\",\"productName\":\"Item_B\"}]}
However, when I try to decode it the result is null
$order = $_GET['orderSummary'];
$data = json_decode($order,true);
echo "<PRE>";
var_dump($data); die();
//displays the following
<PRE>NULL
Is it not properly formatted?
Run the input string through stripslashes() first.
$input = '{\"orderInfo\":[{\"itemNumber\":\"1\",\"quantity\":\"3\",\"price\":\"5.99\",\"productName\":\"Item_B\"}]}';
print_r(json_decode(stripslashes($input)));
Output
stdClass Object
(
[orderInfo] => Array
(
[0] => stdClass Object
(
[itemNumber] => 1
[quantity] => 3
[price] => 5.99
[productName] => Item_B
)
)
)
Demo
Alternatively
Turn off magic_quotes_gpc. Considering that it has been deprecated (and removed in 5.4), this the better option.

Categories