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'];
I am trying to echo a json-encoded array which consist of an array but i dont know it is not letting me print that thing. Here's my code:
<?php
include_once('confi.php');
header('Content-type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$lastRecord = isset($_POST['lastRecordID']) ?
mysql_real_escape_string($_POST['lastRecordID']) : "";
$queryForTotalRec = mysql_query("SELECT customer_id FROM `WebServiceTesting`.`sapphire` ORDER BY customer_id DESC LIMIT 1");
$total_rec = mysql_fetch_row($queryForTotalRec);
if($total_rec){
$queryForAllRecords = "SELECT * FROM `WebServiceTesting`.`sapphire` WHERE customer_ID BETWEEN %d AND %d";
$get_all_recs = mysql_query(sprintf($queryForAllRecords, $lastRecord, $total_rec[0]));
$json = array();
while($row = mysql_fetch_assoc($get_all_recs)){
$json[] = array("Status" => 1, "NewRecord" => $row);
}
print_r($json);
echo json_encode($json);
}else{
$json = array("status" => 0, "Error_Message" => mysql_error());
echo json_encode($json);
}
}else{
$json = array("status" => 0, "Error_Message" => "Request Method not correct");
echo json_encode($json);
}
#mysql_close($conn);
Errors:
Malformed JSON: Unexpected 'A' sometimes 'I'
When i am deleting the print_r line iam getting:
No response received
When i am printing the count of $json array iam getting a count of 153 but NO OTHER output.
Things i've tried:
i read in some solutions to similar problems that u need to use array_values()
for e.g:
echo json_encode(array_values($json));
same response: 'No response received'
I've also tried putting echo $json inside loop which I know that is conceptually wrong but still and got expected error 'Syntax error'
Also, i tried echoing through foreach no luck Syntax error but i can see output in raw but cannot validate the json.
Just for the info on print_r this is the response:
Array (
[0] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1241
[firstName] => Katy
[lastName] => Lest
[email] => klest#yahoo.com [phone] => 787012425
)
)
[1] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1242
[firstName] => Hanah
[lastName] => Morrisn
[email] => road#gmail.com
[phone] => 144221275 )
)
[2] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1243
[firstName] => James
[lastName] => McGrath
[email] => rosamcgrath#hotmail.com
[phone] => 79684312 )
)
)
Just found a sort of answer to this i am still looking for a reason if anyone can help in that please. The number of Records i was pulling were 150+ so i just tried with 50 records at a time and it worked perfectly. Anyone know how can i actually allocate more memory to my array so that it can hold all the required data at once only ?
I have also tried by giving accurate index as well i thought that array goes out of memory but this even not working:
$json = new SplFixedArray($difference);
Your assistance would be very much appreciated.
Stab into the dark: some of your database rows contain non-ASCII characters (e.g. ü, é and such). Your database connection is set to latin1, so the data is not UTF-8 encoded. json_encode requires UTF-8 encoded data. If you fetch enough rows, there will be rows with such non-UTF-8 data in there, and json_encode fails. With few enough rows you happen to not hit those problematic rows.
Test this by outputting echo json_last_error_msg(); after json_encode.
Set your database connection to UTF-8. See here how to do so: UTF-8 all the way through
The reason why your browser complains about invalid JSON when you include a print_r is simple: because then PHP outputs a lot of garbage which isn't JSON, which the browser can't decode as JSON.
Simply Use json_decode() you will get the result you need..
$array = json_decode($json, true);
echo "<pre>"; print_r($array);
Array
(
[0] => Array
(
[Status] => 1
[NewRecord] => Array
(
[fname] => xyz
[lname] => abc
[gender] => male
)
)
[1] => Array
(
[Status] => 1
[NewRecord] => Array
(
[fname] => 123
[lname] => 456
[gender] => male
)
)
[2] => Array
(
[Status] => 1
[NewRecord] => Array
(
[fname] => demo
[lname] => vvv
[gender] => female
)
)
)
I have the following Json
[response] => stdClass Object
(
[status] => 1
[httpStatus] => 200
[data] => Array
(
[0] => 230
[1] => 1956
[2] => 1958
[3] => 2294
)
How do i get the data array out of the response?
I know this is quite simple.
update
Here is some of my source code
$url = $base . http_build_query( $params );
$result = file_get_contents( $url );
echo '<pre>';
print_r( json_decode( $result ) );
echo '</pre>';
$data = $result->response->data;
print_r($data);
$json_object = json_decode($result);
print_r($json_object->response->data);
In PHP, -> is the object operator (or arrow). I'd encourage you to read more about Objects in PHP and json_decode().
That is not JSON, that is a PHP array or object. You didn't provide enough info to tell which one it is.
You can access the data array from it using either:
$data = $arr['response']->data;
Or:
$data = $obj->response->data;
Replace $arr or $obj with the actual variable name.
Edit
Your variable contains a string, because after decoding it you did not save the result. Try the following code:
$url = $base . http_build_query( $params );
$json = file_get_contents( $url );
$result = json_decode($json);
$data = $result->response->data;
echo '<pre>',print_r($data, true),'</pre>';
simply like this :-
[response] => stdClass Object
(
[status] => 1
[httpStatus] => 200
[data] => Array
(
[0] => 230
[1] => 1956
[2] => 1958
[3] => 2294
)
$json_data=json_decode($response,true);
I need some help. I have a variable containing this string;
[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"},{"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]
I need to retrieve the id and value for each pair and make it any array in PHP.
You can use json_decode and pass the second param as true so it returns an array like this
$json = '[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"},{"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]';
$decoded = json_decode($json,true);
print_r($decoded);
Working Example
Output would be
Array
(
[0] => Array
(
[id] => 17
[value] => 123456789
)
[1] => Array
(
[id] => 18
[value] => 2012-06-13
)
[2] => Array
(
[id] => 19
[value] => Kampala
)
[3] => Array
(
[id] => 20
[value] => 1
)
.......
)
Which you can loop through using foreach like.
foreach($decoded as $de){
// access id with $de['id']
// access value with $de['value']
}
You have got an json string. You can convert it to an array by using function json_decode
Check this code .
$str = '[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"}, {"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]';
$array = json_decode($str);
foreach($array as $temp){
echo "ID : ".$temp->id."\t Value: ".$temp->value;
echo "<br />";
}
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']);