Read Json Object Using PHP - php

I am trying to read a json object using php as follows
$jsonObject = file_get_contents("http://10.12.12.189:9080/NonMotorServices/CommonServices.svc/FetchCurrency");
$jsonres = json_decode($jsonObject, true);
Following are the content of the object
{"Data":"[{\"CurrencySymbol\":\"AU$\",\"CurrencyDescription\":\"Austrailian Dollar\",\"CurrencyRate\":135.42,\"CurrencyType\":\"AUD\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":135.42},{\"CurrencySymbol\":\"£.\",\"CurrencyDescription\":\"British pound sterling\",\"CurrencyRate\":212.62,\"CurrencyType\":\"GBP\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":212.62},{\"CurrencySymbol\":\"EURO\",\"CurrencyDescription\":\"Euro\",\"CurrencyRate\":171.2,\"CurrencyType\":\"EUR\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":171.2},{\"CurrencySymbol\":\"¥.\",\"CurrencyDescription\":\"Japanese yen\",\"CurrencyRate\":1.6809,\"CurrencyType\":\"JPY\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":1.6809},{\"CurrencySymbol\":\"SIN$\",\"CurrencyDescription\":\"Singapore Dollar\",\"CurrencyRate\":107.3,\"CurrencyType\":\"SGD\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":107.3},{\"CurrencySymbol\":\"Rs.\",\"CurrencyDescription\":\"Sri Lankan Rupees\",\"CurrencyRate\":1,\"CurrencyType\":\"LKR\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":1},{\"CurrencySymbol\":\"CHF\",\"CurrencyDescription\":\"Swiss Frank\",\"CurrencyRate\":141.71,\"CurrencyType\":\"CHF\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":141.71},{\"CurrencySymbol\":\"US$.\",\"CurrencyDescription\":\"United States dollar\",\"CurrencyRate\":135,\"CurrencyType\":\"USD\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":137}]","ID":1}
I need to list down currency in a html selection and i used following to do so.
echo '<select>';
foreach($jsonres->Data as $option)
{ echo '<option value=' . $option->CurrencyDescription . '>' . $option->CurrencyDescription . '</option>';
}
echo '</select>';
I am getting an empty selection as a result and i need to load 'CurrencyDescription ' as option value. Please help me with this. and please explain what is the error i made because i am new to php and json.
Full Code as follows
<?php
$jsonObject = file_get_contents("http://10.12.12.189:9080/NonMotorServices/CommonServices.svc/FetchCurrency");
$jsonres = json_decode($jsonObject, true);
echo '<select>';
foreach($jsonres->Data as $option)
{ echo '<option value=' . $option->CurrencyDescription . '>' . $option->CurrencyDescription . '</option>';
}
echo '</select>';
?>

$jsonres is actually an array.
This is because true is being passed as the second parameter to json_decode. If you, in fact, do want $jsonres to be an object, then just use json_decode($jsonObject);.
An easy way to check what your variable contains is to use the var_dump function.
$jsonres = json_decode($jsonObject);
var_dump($jsonres);
Also, be sure you have error_reporting turned on and set to E_ALL. The following code, $jsonres->Data, should be causing PHP to emit a "PHP Notice".

Finally I Solve The Problem. Here is My Solution
<select>
<?php
$jsonObject = file_get_contents("http://10.12.12.189:9080/NonMotorServices/CommonServices.svc/FetchCurrency");
$jsonres = json_decode($jsonObject,true);
$val = $jsonres['Data'];
$phpArray = json_decode($val, true);
foreach ($phpArray as $key => $value) {
$curName;
foreach ($value as $k => $v) {
if($k === 'CurrencyDescription'){
$curName=$v;}
}
echo '<option value=' . $curName. '>' . $curName. '</option>';
}
?>
</select>

Related

How do I get one json value value each?

in this my php code
echo $_POST[result];
in this my php result
{
"result_code":0,
"err_cd":"",
"result_msg":"",
"store_id":"M20C2685",
"status":"APPROVED",
"order_no":"600a2a044c9be",
"tr_no":725,
"tr_price":1000,
"pay_price":1000,
"approved_day":"20210122",
"approved_time":"102744",
"param1":"",
"param2":""
}
I want to print out each value one by one. What should I do?
json_decode Parsing JSON
<?php
$str = '{"result_code":0,
"err_cd":"",
"result_msg":"",
"store_id":"M20C2685",
"status":"APPROVED",
"order_no":"600a2a044c9be",
"tr_no":725,
"tr_price":1000,
"pay_price":1000,
"approved_day":"20210122",
"approved_time":"102744",
"param1":"",
"param2":""
}';
$arr = json_decode($str, true);
echo $arr['err_cd'] . PHP_EOL;
echo $arr['result_msg'] . PHP_EOL;
echo $arr['store_id'] . PHP_EOL;
echo $arr['status'] . PHP_EOL;
// ......
// Circulates each value in the array
foreach ($arr as $item) {
echo $item . PHP_EOL;
}

Input <select> selected is not working correctly in PHP by comparing 2 arrays

I have
3 <select></select>
with 8 options inside (Array_1 with 8 position). All options value are the same.
What i am trying to do is that I want to make the Value in Array_2 to be the Selected value.
However, looks like my loop is not working correctly.
$array_1[]="value1";
$array_1[]="value2";
$array_1[]="value3";
$array_1[]="value4";
$array_1[]="value5";
$array_1[]="value6";
$array_1[]="value7";
$array_1[]="value8";
$array_2[]="value1";
$array_2[]="value3";
$array_2[]="value4";
for($i=0;$i<count($array_2);$i++){
echo '<select name="product_header_image[]">';
for($b=0;$b<count($array_1);$b++){
if(in_array($array_2[$i],$array_1)){
echo '<option selected VALUE="'.$array_1[$b].'" >'.$array_1[$b].'</option>';
}else{
echo '<option VALUE="'.$array_1[$b].'" >'.$array_1[$b].'</option>';
}
}
echo '</select>';
echo '<br>';
}
Anyone know whats wrong with my coding? what I want to achieve is the right hand side of the screenshot.
You need to replace this check:
if(in_array($array_2[$i], $array_1)) {
...
}
on this:
if($array_2[$i] == $array_1[$b]) {
...
}
Demo here
Not sure I understand your scenario, but this might be what you are looking for. It generates a dropdown with all the elements from both arrays, and highlights the selected ones.
$array_1[]="value1";
$array_1[]="value2";
$array_1[]="value3";
$array_1[]="value4";
$array_1[]="value5";
$array_1[]="value6";
$array_1[]="value7";
$array_1[]="value8";
$array_2[]="value1";
$array_2[]="value3";
$array_2[]="value4";
echo '<select name="product_header_image[]" multiple>';
foreach ($array_1 as $elem1) {
echo '<option VALUE="'. $elem1 .'" >' . $elem1 .'</option>';
}
foreach ($array_2 as $elem2) {
$selected = '';
if( in_array($elem2, $array_1) ) $selected = 'selected ';
echo '<option '. $selected . 'VALUE="' . $elem2 . '" >'.$elem2.'</option>';
}
echo '</select>';
echo '<br>';

How to print jSON values with loop

I am using the following code to print the output of the jSON response but when I try to print
echo $obj->HotelListResponse->customerSessionId; // This is working.
echo $obj->HotelListResponse->HotelList->HotelSummary->name; // This is not working.
When the response contains only one node then its printing perfectly but when there are multiple nodes with same name then its not printing. I tried using foreach just like the below. I also tried using while loop but still I am unable to print the list of hotel names.
My jSON decoded output is like http://pastebin.com/Fr21DkEk
Total code:
$url = "https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55505&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_AU&currencyCode=AUD&xml=<HotelListRequest><city>Brisbane</city><stateProvinceCode>QLD</stateProvinceCode><countryCode>AU</countryCode><arrivalDate>10/16/2014</arrivalDate><departureDate>10/18/2014</departureDate><RoomGroup><Room><numberOfAdults>2</numberOfAdults></Room></RoomGroup><numberOfResults>25</numberOfResults></HotelListRequest>";
$json = file_get_contents($url);
$obj = json_decode($json);
foreach($obj as $val) {
echo $val->HotelListResponse->HotelList->HotelSummary->name;
}
Try this
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
echo $val->name . '<br/>';
}
HotelSummary is an array:
echo $val->HotelListResponse->HotelList->HotelSummary[0]->name;
If you want all of the hotel summaries:
foreach($obj as $val) {
foreach($val->HotelListResponse->HotelList->HotelSummary as $sum) {
echo $sum->name;
}
}
Yes you can directly access them inside the foreach. Like this:
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
// ^^
// since you're interested on just names, you can point it directly on that object, then each of that batch is in `$val`
echo $val->name . '<br/>';
}
// or start from the parent
foreach($obj as $values) {
$customerSessionId = $values->customerSessionId;
echo $customerSessionId . '<hr/>';
$hotelList = $values->HotelList;
foreach($hotelList->HotelSummary as $hotelsummary) {
echo $hotelsummary->name . '<br/>';
}
}

PHP foreach - parsed json from URL

I have a JSON file called from an URL. I've checked and I'm getting the the data from the URL.
I've tried a lot, but I can't get the loop foreach to work - what is wrong?
<?php
$url = 'http://banen.klintmx.dk/json/ba-simple-proxy.php?url=api.autoit.dk/car/GetCarsExtended/59efc61e-ceb2-463b-af39-80348d771999';
$json= file_get_contents($url);
$data = json_decode($json);
$rows = $data->{'contents'};
foreach($rows as $row) {
echo '<p>';
$FabrikatNavn = $row->{'contents'}->{'FabrikatNavn'};
$ModelNavn = $row->{'contents'}->{'ModelNavn'};
$PrisDetailDkk = $row->{'contents'}->{'PrisDetailDkk'};
echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
echo '</p>';
}
?>
The actual problem is you trying to access content object again. Just change your foreach snippet with,
foreach ($rows as $row) {
echo '<p>';
$FabrikatNavn = $row->FabrikatNavn;
$ModelNavn = $row->ModelNavn;
$PrisDetailDkk = $row->PrisDetailDkk;
echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
echo '</p>';
}
DEMO.
Use json_decode($data, true) so that it parses the JSON content into a PHP array. So it will be something like
$rows = $data['contents'];
foreach($rows as $row) {
echo '<p>';
$FabrikatNavn = $row['contents']['FabrikatNavn'];
$ModelNavn = $row['contents']['ModelNavn'];
$PrisDetailDkk = $row['contents']['PrisDetailDkk'];
echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
echo '</p>';
}
Take a look at using json_decode($json, true) as this will convert the data to an associative array which seems to be the way you are approaching the solution.
Check the output by printing with var_dump() or print_r()
Try like this
$data = json_decode($json,true); //decode json result as array and thenloop it
print '<pre>';
print_r($data);
foreach($data as $row){
//do something here
}

Modify function which dynamically populates select elements to use arrays from db

I'm trying to modify a function that I've been using to dynamically populate <select> element to use arrays from a database. The original function used hard-coded arrays to populate the elements, and pre-selected the option which matched the db value.
The revised function creates the element, but it's only adding the first value from the db. How can I modify it so that it will loop through all the values that should be added to the <select> element?
PHP Function and Query
<?php
function printSelectOptions($dataArray, $currentSelection) {
foreach ($dataArray as $key => $value) {
echo '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . $value . '</option>';
}
}
try {
$stmt = $conn->prepare("SELECT * FROM student");
$stmt->execute();
}catch(PDOException $e) {
echo $e->getMessage();
}
$row = $stmt->fetch();
?>
Populate Select Element
<select name="fname">
<?php
echo printSelectOptions(array($row['fname']));
?>
</select>
The Original Function & Code for Populating an Element
function printSelectOptions($dataArray, $currentSelection) {
foreach ($dataArray as $key => $value) {
echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
}
}
<select name="fname">
<?php
$options = array("John"=>"John", "Mary"=>"Mary", "Elizabeth"=>"Elizabeth");
$selected = $row['fname'];
echo printSelectOptions($options, $selected);
?>
</select>
Since you have only fetched a single row via fetch(), only a single value is getting passed into your function printSelectOptions(). Instead, get all rows via fetchAll()
and modify your function to receive the full array, plus a string which is the column name (array key) you want to print from.
// All rows into $rows...
$rows = $stmt->fetchAll();
// Make the function accept the full 2D array, and
// a string key which is the field name to list out:
function printSelectOptions($dataArray, $currentSelection, $fieldname) {
// String to hold output
$output = '';
foreach ($dataArray as $key => $value) {
// Rather than echo here, accumulate each option into the $output string
// Use the $fieldname as a key to $value which is now an array...
$output .= '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
}
return $output;
}
Then call the function as:
echo printSelectOptions($rows, $currentSelection, 'fname');
The way it is right now, the option's value attribute is populated by the array key, which would be numbered from zero. That's similar to your original array version, but it might be more useful to specify another column name like id as the key column.
// This one also takes a $valuename to use in place of $key...
function printSelectOptions($dataArray, $currentSelection, $valuename, $fieldname) {
// String to hold output
$output = '';
foreach ($dataArray as $key => $value) {
// Rather than echo here, accumulate each option into the $output string
// Use the $fieldname as a key to $value which is now an array...
$output .= '<option ' . (($value[$valuename] == $currentSelection)) . ' value="' . $value[$valuename] . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
}
return $output;
}
And would be called as:
echo printSelectOptions($rows, $currentSelection, 'id', 'fname');

Categories