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'];
Related
This is my example json data
[
{"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},
{"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},
{"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},
{"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}
]
and i want to save the data to mysql with php, field product_id, price, status, name, anyone can help me please
my problem is, i dont know better code for me in php
You could use PHP
json_decode()
function to convert that json string into PHP variables.
You could then get those values and save them to the MySQL Database;
Source json_decode PHP Manual
you can use json_decode(). it takes a JSON encoded string and converts it into a PHP variable.
<?php
$json_data = '[{"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},{"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},{"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},{"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}]';
$array_data = json_decode($json_data);
echo '<pre>';
print_r($array_data);
foreach ($array_data as $event) {
echo 'Product_id:' . $event->kode;
echo "<br>";
echo 'status:' . $event->status;
echo "<br>";
}
then output is
Array
(
[0] => stdClass Object
(
[kode] => AX5
[harga] => 6200
[status] => 1
[nama] => AXIS 5
)
[1] => stdClass Object
(
[kode] => AX10
[harga] => 11250
[status] => 1
[nama] => AXIS 10
)
[2] => stdClass Object
(
[kode] => AX25
[harga] => 25750
[status] => 1
[nama] => AXIS 25
)
[3] => stdClass Object
(
[kode] => AX50
[harga] => 50800
[status] => 1
[nama] => AXIS 50
)
)
Product_id:AX5
status:1
Product_id:AX10
status:1
Product_id:AX25
status:1
Product_id:AX50
status:1
for more information
http://php.net/manual/en/function.json-decode.php
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}}}
I am retrieving a multidimensional php array (I think) from an API, now all of the values return perfectly and when I dump the array with print_r I get this:
Event Object
(
[title] => test
[link] => google.com
[updated] => 2013-03-06T12:08:56.521-05:00
[id] => test
[name] => Copy of Copy of Copy of Mar 05, 2013 - TEST4
[description] =>
[registered] => 2
[createdDate] => 2013-03-06T12:08:56.521-05:00
[status] => COMPLETE
[eventType] => OTHER
[eventLocation] => EventLocation Object
(
[location] => test
[addr1] => test
[addr2] =>
[addr3] =>
[city] => madrid
[state] => andalucia
[country] =>
[postalCode] => 06103
)
[registrationUrl] => https://google.com
[startDate] => 2013-03-07T13:00:00-05:00
[endDate] => 2013-03-07T13:00:00-05:00
[publishDate] => 2013-03-06T12:11:15.958-05:00
[attendedCount] => 0
[cancelledCount] => 0
[eventFeeRequired] => FALSE
[currencyType] => USD
[paymentOptions] => Array
(
)
[registrationTypes] => Array
(
[0] => RegistrationType Object
(
[name] =>
[registrationLimit] =>
[registrationClosedManually] =>
[guestLimit] =>
[ticketing] =>
[eventFees] => Array
(
)
)
)
)
Now bumbling through wit my basic PHP i have found that i can list all of the first array items from [title] to [eventType] like this:
<?php
// get details for the first event returned
$Event = $ConstantContact->getEventDetails($events['events'][0]);
reset($Event);
while (list($key, $value) = each($Event)) {
echo "$key => $value \r\n<br/>";
}
?>
my question: All I need to do it retrieve [title] and [startDate] I don't need the rest now I could just hide the rest using Js and css but i am sure i am just being an idiot and there is an easier way to traverse this array so it only spits out the two values i need.
How do i do this?
You do not have to traverse the whole object. Just access the properties you want:
$title = $Event->title;
$startDate = $Event->startDate;
// or
echo $Event->title;
echo $Event->startDate;
It's actually an object - not an (associative) array!
What's the difference?
An object is an instance of a class. A class has methods and attributes (member variables).
Unlike C++ or some other OOP languages, you can define attributes dynamically without declaring them in the class declaration.
An array is simply a container for keys and their values.
It seems that it's not an array but an object so something like this:
echo $Event->title;
echo $Event->startDate;
Is it ...
<?php
// get details for the first event returned
$Event = $ConstantContact->getEventDetails($events['events'][0]);
reset($Event);
echo $Event->$title . "<br/>";
echo $Event->$startDate . "<br/>";
?>
? Or am I too simple?
$json = file_get_contents('outputsjson.php');
The file encodes an array then just echoes it as this (and echo $json outputs this):
{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}}
Now I'm trying to decode it from another page like this:
$myarray = json_decode($json, true);
print_r($myarray);
This outputs nothing, no errors, nothing!
Try this instead (you are mixing " and ' [single quotes instead of double quotes on the string]):
$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}} ';
$myarray = json_decode($json, true);
print_r($myarray);
And your result:
Array
(
[theList] => Array
(
[1] => Array
(
[name] => DSC04156.JPG
[title] => DSC04156.JPG
[width] => 3264
)
[2] => Array
(
[name] => DSC04157.JPG
[title] => DSC04157.JPG
[width] => 3264
)
[3] => Array
(
[name] => DSC04158.JPG
[title] => DSC04158.JPG
[width] => 3264
)
[4] => Array
(
[name] => DSC04159.JPG
[title] => DSC04159.JPG
[width] => 3264
)
)
)
Try wrapping the json string in single quotes instead of double quotes:
$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}}';
I had no problems executing the following code:
$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}}';
$myarray = json_decode($json, true);
print_r($myarray);
My guess would be that the file you are trying to read from does not exist. Remember that, if you are using Linux, file names are case-sensitive. Use the file_exists() function to check this:
var_dump(file_exists('outputsjson.php'));
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']);