This is an example item:
SimpleXMLElement Object
(
[#attributes] => Array
(
[displayInfoId] => 62116
[durability] => 100
[gem0Id] => 41401
[gem1Id] => 40123
[gem2Id] => 0
[gemIcon0] => inv_jewelcrafting_shadowspirit_02
[gemIcon1] => inv_jewelcrafting_gem_37
[icon] => inv_helmet_98
[id] => 48592
[level] => 245
[maxDurability] => 100
[name] => Liadrin's Headpiece of Triumph
[permanentEnchantIcon] => ability_warrior_shieldmastery
[permanentEnchantItemId] => 44876
[permanentenchant] => 3819
[pickUp] => PickUpLargeChain
[putDown] => PutDownLArgeChain
[randomPropertiesId] => 0
[rarity] => 4
[seed] => 0
[slot] => 0
)
)
I'm trying to get a JSON object with each item, but there's about 17 or something, and if I try to json_encode() it's giving me "#attributes" as an object containing all the stuff I want. Help?
Something like this:
<?php
$sxm = new SimpleXMLElement("<a name=\"kkk\" other=\"foo\"/>");
$attrs = $sxm->attributes();
var_dump(json_encode(reset($attrs)));
gives:
string(28) "{"name":"kkk","other":"foo"}"
The problem you were experiencing was because $xmlObj->attributes() returns a SimpleXMLElement that, when converted as an array, is an array with the key "#attributes" and a value with an array that actually has the attributes as (name => value) pairs.
How about this
$jsonArray = array();
foreach ($xmlObj->attributes() as $attr => $value) {
$jsonArray[$attr] = (string)$value;
}
$jsonString = json_encode($jsonArray);
Edit: You may also be able to simply use
$jsonString = json_encode($xmlObj->attributes());
however I'm not sure if the attribute values are returned as strings or objects (edit - turns out you can't. See Artefacto's solution).
How about this?
$array = (array)$simplexml->node->attributes();
$jsonArray = json_encode($array['#attributes']);
Related
I have this output from a JSON. How can I get one element (for example "etternavn" ) into a PHP variable. This is the output I get for the whole thing:
stdClass Object (
[hitLinesBeforeFilter] => 1
[userID] => 632
[1] => stdClass Object (
[listing] => stdClass Object (
[table] => listing
[id] => 1402864
[duplicates] => Array (
[0] => stdClass Object (
[table] => listing
[id] => 1402864:0
[idlinje] => D1FIJFT000
[tlfnr] => 41428798
[etternavn] => Bumpy Bones Interactive Cornelius Gutsu
[veinavn] => Hans Nielsen Hauges vei
[husnr] => 48F
[postnr] => 1523
[virkkode] => N
[apparattype] => M
[kilde] => D
[foretaksnr] => 998209609
[bransjekode] => 15636
[prioritet] => 0
[kommunenr] => 104
[poststed] => Moss
[kommune] => Moss
[fylke] => Østfold
[landsdel] => Ø
[bransjebokmaal] => Internettdesign og programmering
[bransjenynorsk] => Internett design og programmering
)
)
)
)
[dummy] =>
)
The PHP code is the following:
$json = utf8_encode(file_get_contents($url, 'UTF-8'));
$data = json_decode($json);
print_r($data->result);
I have tried echo $data->etternavn;
I know this might be a simple question, sorry. I'm not good with coding.
You can do this:
<?php
$json = utf8_encode(file_get_contents($url, 'UTF-8'));
$data = json_decode($json, true);
print_r($data['result'][1]['listing']['duplicates'][0]['etternavn']);
?>
You have to traverse through this complex structure. To get etternavn you need to do this:
$data = json_decode($json);
echo $data->result->{1}->listing->duplicates->{0}->etternavn;
Or as suggested in comments, pass next parameter of json_decode to true. Which will convert it into array.
$data = json_decode($json, true);
echo $data['result'][1]['listing']['duplicates'][0]['etternavn'];
Having a problem on solving this code. These are the arrays
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => delux
[price] => 213
[description] =>
[tv] => 0
[breakfast] => 0
[park] => 0
[wifi] => 0
[ac] => 0
[occupancy] =>
[size] =>
[view] =>
[service] =>
[terrace] => 0
[pickup] => 0
[internet] => 0
[gym] => 0
[note] =>
[room_details] => {"img":["images/logo2.png","images/logo.png"]}
)
[1] => stdClass Object
(
[id] => 2
[name] => hjghj
[price] => 234
[description] =>
[tv] => 0
[breakfast] => 0
[park] => 0
[wifi] => 0
[ac] => 0
[occupancy] =>
[size] =>
[view] =>
[service] =>
[terrace] => 0
[pickup] => 0
[internet] => 0
[gym] => 0
[note] =>
[room_details] =>
)
)
I want to echo the per images under room_details to show like this
images/logo2.png
images/logo.png
Here's my code
foreach ($roomandsuits as $i => $item) {
$array_links = json_decode($item->room_details, true); {
foreach ($array_links as $key => $value) {
foreach ($value as $content) {
echo $content;
}
}
}
}
Error in 3rd line and shows like this
images/logo2.png
images/logo.png
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\resort\modules\mod_roomandsuits\tmpl\default.php on line 10
images/logo.png
Try the below code. I added the details with comments.
foreach ($roomandsuits as $i => $item) {
if($item->room_details){ //check if value of $item->'room_details' not null
$room_details = json_decode($item->room_details, true); //decode the json data
if(!empty($room_details)){ //Check if room_details is not empty array
$room = $room_details['img'];
array_walk($room, function($value){ //using array_walk gate the value of room_details
echo $value .'<br/>';
});
}
}
}
DEMO
You need to check you're working with an array before passing it to foreach.
The second element in $roomandsuits has an empty 'room_details'. Regardless, you're putting it through json_decode() and immediately passing to foreach.
$array_links = json_decode($item->room_details, true); // there was a misplaced opening brace here previously...
if (!is_array($array_links)) {
continue;
}
foreach ($array_links as $key => $value) {
Your deep json strings are structurally different. Decoding the first generates an img keyed array containing two strings. The second has is null or an empty string (your post doesn't reveal that for us). Your final foreach() is trying to iterate a non-iterable data type -- this is the cause of your issue.
I might suggest a refactor to avoid so many foreach() structures...
You can isolate the room_details column with array_column() after casting the input array as an array.
It is important that you not only check that the subarray is not empty, but that it actually contains the img key. If it does, my script will assume that it is an indexed array.
Then iterate the collection of json strings, decode them, then unpack (with the splat operator ...) and push them into your result array.
When finished building the result array, implode the elements with <br>.
Code: (Demo)
$array = [
(object)[
'id' => 1,
'name' => 'delux',
'room_details' => '{"img":["images/logo2.png","images/logo.png"]}'
],
(object)[
'id' => 2,
'name' => 'hjghj',
'room_details' => ''
]
];
$images = [];
foreach (array_column((array)$array, 'room_details') as $json) {
$obj = json_decode($json);
if (isset($obj->img)) {
array_push($images, ...$obj->img);
}
}
echo implode("\n", $images); // implode with <br> for html linebreaks
Output:
images/logo2.png
images/logo.png
One advantage of using array_column() is if room_details does not exist for some reason in one of the objects, it will be omitted from the looping process. This avoids the need to check if room_details isset() before trying to decode it.
I have a JSON array object in which I am trying to append an array to one of the fields.
{"email":"bar#foo.org","password":"password","devices":{}}
print_r($arr) gives me:
Array ( [0] => {
"email":"bar#foo.org",
"password":"password",
"devices":{}
}
[1] => {
"email":"bar2#foo.org",
"password":"password",
"devices":{}
}
)
where $device_info is an array of structure:
array(
"number" => $phoneNumber,
"type" => "CellPhone",
"config" => array(
"batteryLevel" => 100,
"Lowbatterylevel" => 10,
)
I am trying to do this:
array_push($arr[$i]["devices"],$device_info);
which throws an error "Warning: Illegal string offset 'devices' "
I saw some other similar questions in StackOverflow but the solutions didn't work. Can someone point out what I'm doing wrong here? Thanks in advance.
You are not looking closely enough at your original JSON String or the full output from your print_r()
That is an Object containing properties and devices property is an object as well that contains it own properies
Here is some sample code to get your going
$s = '{"email":"bar#foo.org","password":"password","devices":{}}';
$j = json_decode($s);
$o = new stdClass();
$o->number = 999;
$o->type = "CellPhone";
$o->config = array("batteryLevel" => 100,"Lowbatterylevel" => 10);
$j->devices = $o;
print_r($j);
echo json_encode($j);
Results are
stdClass Object
(
[email] => bar#foo.org
[password] => password
[devices] => stdClass Object
(
[number] => 999
[type] => CellPhone
[config] => Array
(
[batteryLevel] => 100
[Lowbatterylevel] => 10
)
)
)
{"email":"bar#foo.org","password":"password","devices":{"number":999,"type":"CellPhone","config":{"batteryLevel":100,"Lowbatterylevel":10}}}
To me this looks like you confuse objects and arrays in your approach...
That json encoded string you posted does not encode an array but an object. So you have to treat it as such. Take a look at this simple demonstration code:
<?php
$payload = [
"number" => '01234567890',
"type" => "CellPhone",
"config" => [
"batteryLevel" => 100,
"Lowbatterylevel" => 10
]
];
$input = '{"email":"bar#foo.org","password":"password","devices":{}}';
$data = json_decode($input);
$data->devices = $payload;
$output = json_encode($data);
print_r(json_decode($output));
print_r($output);
The output ob above obviously is:
stdClass Object
(
[email] => bar#foo.org
[password] => password
[devices] => stdClass Object
(
[number] => 01234567890
[type] => CellPhone
[config] => stdClass Object
(
[batteryLevel] => 100
[Lowbatterylevel] => 10
)
)
)
{"email":"bar#foo.org","password":"password","devices":{"number":"01234567890","type":"CellPhone","config":{"batteryLevel":100,"Lowbatterylevel":10}}}
This post describes how to remove an element of an associative array with Unset i.e unset($array['key1']);
I have this array:
Array
(
[queryLocator] =>
[done] => 1
[records] => Array
(
[0] => stdClass Object
(
[Id] =>
[CreatedDate] => 2016-08-28T14:43:45.000Z
[Leader__c] => GF
[Location__c] => Postbridge
[Service_Date__c] => 2016-09-03
[Service_Time__c] => 14:30
[Service_Type__c] => Baptism
)
)
[size] => 42
[pointer] => 0
[QueryResultsf] => SforceEnterpriseClient Object
(
[sforce:protected] => SoapClient Object
(
[trace] => 1
[compression] => 32
[_encoding] => utf-8
[_features] => 1
[_user_agent] => salesforce-toolkit-php/20.0
[_soap_version] => 1
[sdl] => Resource id #8
[packageVersionHeader:protected] =>
[client_id:protected] =>
)
)
)
I want to delete the key [queryLocator], replace the key [done] with [total], replace the key [records] with [rows] and delete all subsequent keys i.e [size], [pointer] etc.
Using unset, i.e unset($array['queryLocator']); has no effect.
What am I doing wrong ? Thanks.
Here is the code that achieves what I wanted - taking output from a Sales Force query and formatting it as required by a EasyUI datagrid.
//--Get the Sales Force Data
$response = $mySforceConnection->query($query);
//--Encode and decode - for some reason
$data = json_encode((array)$response);
$x = json_decode($data,true);
//--Empty Array
$q = array();
//--Add array element for number records
$q['total'] = $numRecs;
//--Copy the array element from original query with data
$q['rows'] = $x['records'];
//--JSON Encode the new array
$y = json_encode($q);
//--Return the array to Ajax call
echo ($y);
And here's a snippet of the validated JSON..
{
"total":193,
"rows":[
{
"Id":null,
"CreatedDate":"2016-08-28T14:43:45.000Z",
"Leader__c":"GF",
"Location__c":"Postbridge",
"Service_Date__c":"2016-09-03",
"Service_Time__c":"14:30",
"Service_Type__c":"Baptism"
},
{
"Id":null,
"CreatedDate":"2016-08-17T20:43:10.000Z",
"Leader__c":"GF",
"Location__c":"Ashburton",
"Service_Date__c":"2016-09-04",
"Service_Time__c":"08:00",
"Service_Type__c":"HC 2"
},
{
"Id":null,
"CreatedDate":"2016-08-17T20:43:10.000Z",
"Leader__c":"GF",
"Location__c":"Bickington",
"Service_Date__c":"2016-09-04",
"Service_Time__c":"09:00",
"Service_Type__c":"HC 2"
},
{
"Id":null,
"CreatedDate":"2016-08-17T20:43:10.000Z",
"Leader__c":"MC",
"Location__c":"Holne",
"Service_Date__c":"2016-09-04",
"Service_Time__c":"10:30",
"Service_Type__c":"HC 1"
},
I struggled a bit with the array manipulation but it works. Any code improvement suggestions most welcome !
i have an extern JSON File and no problems to get Airline, Price, etc..
But how can i get [ACE] ?
[success] => 1
[data] => Array
(
[ACE] => Array
(
[0] => Array
(
[price] => 477
[airline] => AB
[flight_number] => 2434
[departure_at] => 2014-08-09T12:30:00Z
[return_at] => 2014-08-24T08:35:00Z
[expires_at] => 2014-04-03T22:46:17Z
)
)
$foo = $json['data']['ACE']; should do it.
Unless you want to get the key from the $data array, in which case:
foreach ($json['data'] as $k=>$v) {
$foo = $k; // this is 'ACE'.
break;
}
Edited as per comment.
['ACE'] is an array?
Your getting the data from it starting with the first - [0]
Then the ['price'] of the first one?