I'm trying to extract some JSON contained in of my XML file and then retrieve the values.
My XML is :
<Vehicle xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://regcheck.org.uk">
<vehicleJson>{
"Description": "RENAULT SCÉNIC III",
"RegistrationYear": "2016",
"CarMake": {
"CurrentTextValue": "RENAULT"
},
"CarModel": {
"CurrentTextValue": "SCÉNIC III"
},
"EngineSize": {
"CurrentTextValue": "5"
},
"FuelType": {
"CurrentTextValue": "DIESEL"
},
"MakeDescription": {
"CurrentTextValue": "RENAULT"
},
"ModelDescription": {
"CurrentTextValue": "SCÉNIC III"
},
"Immobiliser": {
"CurrentTextValue": ""
},
"IndicativeValue": {
"CurrentTextValue": 0
},
"DriverSide": {
"CurrentTextValue": ""
},
"BodyStyle": {
"CurrentTextValue": "MONOSPACE COMPACT"
},
"RegistrationDate": "2016-06-24",
"ImageUrl": "http://immatriculationapi.com/image.aspx/#UkVOQVVMVCBTQ8OJTklDIElJSQ==",
"ExtendedData": {
"anneeSortie": "2016",
"boiteDeVitesse": "",
"carburantVersion": "D",
"carrosserieVersion": "",
"classeSra": "",
"libVersion": "1.5 dCi 1461cm3 110cv ",
"libelleModele": "SCÉNIC III",
"marque": "RE",
"modele": "",
"produit": "",
"puissance": "5",
"version": "",
"cleCarrosserie": "",
"groupeSra": "",
"nbPlace": "5",
"datePremiereMiseCirculation": "24062016",
"questionBatterie": "",
"electrique": "",
"genre": "",
"typeVehicule": "",
"numSerieMoteur": "VF1JZ890H55864144",
"valeurANeufSRA": "",
"niveauRisqueVol": "",
"protectionConstructeur": "",
"puissanceDyn": "110",
"segmentVeh": "",
"KtypeId": "5853",
"EngineCC": "1461",
"Co2": "105",
"Cylinders": "4",
"CNIT": "M10RENVP472E768"
}
}</vehicleJson>
<vehicleData>
<Description>RENAULT SCÉNIC III</Description>
<RegistrationYear>2016</RegistrationYear>
<CarMake>
<CurrentTextValue>RENAULT</CurrentTextValue>
</CarMake>
<CarModel>SCÉNIC III</CarModel>
<BodyStyle>
<CurrentTextValue>MONOSPACE COMPACT</CurrentTextValue>
</BodyStyle>
<EngineSize>
<CurrentTextValue>5</CurrentTextValue>
</EngineSize>
<NumberOfDoors>
<CurrentValue>5</CurrentValue>
</NumberOfDoors>
<Transmission>
<CurrentValue />
</Transmission>
<FuelType>
<CurrentTextValue>DIESEL</CurrentTextValue>
</FuelType>
<Immobiliser>
<CurrentTextValue />
</Immobiliser>
<NumberOfSeats>
<CurrentValue>5</CurrentValue>
</NumberOfSeats>
</vehicleData>
</Vehicle>
Step 1: I'm looking to retrieve the Description and some values contained in ExtendedData :
$xml = simplexml_load_string($my_xml) or die("Error: Cannot create object");
$infos_plaque = json_encode($xml->vehicleJson); // The attribute where the JSON is stored
$array = json_decode($infos_plaque);
echo "<pre>";
print_r($array);
echo "</pre>";
This $array return :
stdClass Object
(
[0] => {
"Description": "RENAULT SCÉNIC III",
"RegistrationYear": "2016",
"CarMake": {
"CurrentTextValue": "RENAULT"
},
"CarModel": {
"CurrentTextValue": "SCÉNIC III"
},
"EngineSize": {
"CurrentTextValue": "5"
},
"FuelType": {
"CurrentTextValue": "DIESEL"
},
"MakeDescription": {
"CurrentTextValue": "RENAULT"
},
"ModelDescription": {
"CurrentTextValue": "SCÉNIC III"
},
"Immobiliser": {
"CurrentTextValue": ""
},
"IndicativeValue": {
"CurrentTextValue": 0
},
"DriverSide": {
"CurrentTextValue": ""
},
"BodyStyle": {
"CurrentTextValue": "MONOSPACE COMPACT"
},
"RegistrationDate": "2016-06-24",
"ImageUrl": "http://immatriculationapi.com/image.aspx/#UkVOQVVMVCBTQ8OJTklDIElJSQ==",
"ExtendedData": {
"anneeSortie": "2016",
"boiteDeVitesse": "",
"carburantVersion": "D",
"carrosserieVersion": "",
"classeSra": "",
"libVersion": "1.5 dCi 1461cm3 110cv ",
"libelleModele": "SCÉNIC III",
"marque": "RE",
"modele": "",
"produit": "",
"puissance": "5",
"version": "",
"cleCarrosserie": "",
"groupeSra": "",
"nbPlace": "5",
"datePremiereMiseCirculation": "24062016",
"questionBatterie": "",
"electrique": "",
"genre": "",
"typeVehicule": "",
"numSerieMoteur": "VF1JZ890H55864144",
"valeurANeufSRA": "",
"niveauRisqueVol": "",
"protectionConstructeur": "",
"puissanceDyn": "110",
"segmentVeh": "",
"KtypeId": "5853",
"EngineCC": "1461",
"Co2": "105",
"Cylinders": "4",
"CNIT": "M10RENVP472E768"
}
}
)
Step 2: I try to retrieve the values by making differents requests:
print_r($array->Description);
print_r($array->{'RegistrationDate'});
print_r($array->{'ExtendedData'}->{'puissance'});
print_r($array->ExtendedData->puissance);
// or :
echo $array->Description;
echo $array->ExtendedData->puissance;
echo $array->ExtendedData->libVersion;
I think there is a problem while encoding the Json, I have tried differents solutions but no success.
You only need to decode the JSON into a PHP data structure. Then you can access its properties
$xml = simplexml_load_string($my_xml);
$data = json_decode($xml->vehicleJson); // 👈 just decode the string
echo $data->Description;
echo $data->ExtendedData->puissance;
echo $data->ExtendedData->libVersion;
Demo ~ https://3v4l.org/ZjE9H
Related
I'd like to get the value of array from multi dimensional array. Let say I have json response from API which I decoded using json_decode() function in php and I want using loop to iterate the data.
$string = $response;
$json_a = json_decode($string, true);
foreach($json_a['withdrawals'] as $item) {
echo $item['withdrawalId']['amount']['currencyCode']. '<br/>';
echo $item['withdrawalId']['terminal']['tid']. '<br/>';
echo $item['withdrawalId']['user']['mid']. '<br/>';
echo $item['servicefee']['masterMerchant']['name']. '<br/>';
echo $item['servicefee']['masterMerchant']['address']['address1']. '<br/>';
}
}
print_r($json_a);
and here's the print out of arrays.
{
"limit": 1,
"offset": 0,
"totalTransactionsCount": 5040,
"acceptedTotalTransactionsCount": 4428,
"acceptedTotalTransactionsValue": 2438928.04,
"rejectedTotalTransactionsCount": 612,
"rejectedTotalTransactionsValue": 499294.04,
"withdrawals": [
{
"withdrawalId": "764353634316",
"status": "approval",
"dateTime": "2016-04-28T09:31:38.145Z",
"localDateTime": "2016-04-28 17:31:38",
"accountType": "CURRENT",
"additionalInfo": "approved",
"batch": "000029",
"smscount": 0
"amount": {
"currencyCode": "EUR",
"value": "399.99"
},
"terminal": {
"tid": "88133332",
"serialNumber": "45435435"
},
"user": {
"name": "John Doe",
"email": "jmeter#joe.com",
"phoneNumber": "546546546",
"role": "OPERATOR",
"subMerchant": {
"name": "Submerchant XXY",
"mid": "MID0000"
"serviceFee": {
"name": "rsf",
"merchantFee": "10.0"
},
"masterMerchant": {
"name": "Master Merchant",
"address": {
"address1": "Mainstreet",
"city": "Cork",
"postcode": "Cork",
"country": {
"countryName": "Philippines",
"countryCode": "PH",
"currencyName": "Philippines Peso",
"currencyCode": "PHP",
}
}
},
"address": {
"address1": "Mainstreet",
"city": "Cork",
"postcode": "Cork",
"country": {
"countryName": "Philippines",
"countryCode": "PH",
"currencyName": "Philippines Peso",
"currencyCode": "PHP",
}
}
}
}
}]}
Write it like this:-
$string = $response;
$json_a = json_decode($string, true);
foreach($json_a['withdrawals'] as $item) {
echo $item['withdrawalId']. '<br/>';
echo $item['amount']['currencyCode']. '<br/>';
echo $item['terminal']['tid']. '<br/>';
echo $item['user']['mid']. '<br/>';
echo $item['user']['masterMerchant']['name']. '<br/>';
echo $item['user']['masterMerchant']['address']['address1']. '<br/>';
}
}
print_r($json_a);
I have 2 records from 2 different query results. I have merged those data. but i have to display unique data depends on vName key.
Here is my result:
{
"val1": "9",
"vName": "abc",
"bname": "",
"cname": "",
"brid": "",
"cmpid": "154",
"logo": "",
"banner": "",
"description": "",
"catids": "",
"type": "company",
"is_nav": "1",
"bigthumb_logo": "",
"compressthumb_logo": "",
"bigthumb_banner": "",
"compressthumb_banner": "",
"sp_ar": "Aperitif"
},
{
"val1": "9",
"vName": "abc",
"bname": "abc",
"cname": "abc",
"brid": "341",
"cmpid": "154",
"logo": "",
"banner": "6c497c72bfec4c694c1cc2c49066e7a1.png",
"description": "http:\/\/www.abc.com\/",
"catids": "9",
"sp_ar": "Aperitif",
"type": "company",
"is_nav": "1",
"bigthumb_logo": "40cbcede9429cdb44895e0e6f4c050d2.png",
"compressthumb_logo": "40cbcede9429cdb44895e0e6f4c050d2.png",
"bigthumb_banner": "6c497c72bfec4c694c1cc2c49066e7a1.png",
"compressthumb_banner": "6c497c72bfec4c694c1cc2c49066e7a1.png"
}
Expected result should be only one of them, compare with vName:
{
"val1": "9",
"vName": "abc",
"bname": "",
"cname": "",
"brid": "",
"cmpid": "154",
"logo": "",
"banner": "",
"description": "",
"catids": "",
"type": "company",
"is_nav": "1",
"bigthumb_logo": "",
"compressthumb_logo": "",
"bigthumb_banner": "",
"compressthumb_banner": "",
"sp_ar": "Aperitif"
}
How can i get the result?
Convert the data into an array where the key is your unique value.
You can do something like:
$data = array('this is your array of data');
$unique = array();
foreach($data as $value) {
if(!array_key_exists($value['vName'], $unique)) {
$unique[$value['vName']] = $value;
}
}
// $unique now contains only arrays with a unique 'vName', using the first it finds in the original list
$new_array = array_values($unique);
Assuming you have a array of associative array stored in $data, the following code will filter it based on vName and store array of associative arrays with unique vName in $filtered_data
$taken = array();
$filtered_data = array_filter($data, function($value) {
global $taken;
if (in_array($value['vName'], $taken)) {
return false;
}
else {
$taken[] = $value['vName'];
return true;
}
});
Here, the variable $taken keeps track of all the vName values that are currently in the $filtered_data. If you find a duplicate vName (that is currently there in $taken), it discards that element.
Try this, it should work for you.
$input = array_map("unserialize", array_unique(array_map("serialize",$input)));
I have a field in a json object I am trying to do a pattern match for but I cannot seem to reach the second layer of the object.
JSON:
{
"1680488": {
"SUBID": "1680488",
"os": "FreeBSD 10 x64",
"ram": "2048 MB",
"disk": "Virtual 40 GB",
"main_ip": "107.191.60.48",
"vcpu_count": "2",
"location": "Tokyo",
"DCID": "25",
"default_password": "4",
"date_created": "2015-02-06 02:27:22",
"pending_charges": 7.61,
"status": "active",
"cost_per_month": "18.00",
"current_bandwidth_gb": 2.706,
"allowed_bandwidth_gb": "600",
"netmask_v4": "255.255.254.0",
"gateway_v4": "107.191.60.1",
"power_status": "running",
"VPSPLANID": "8",
"v6_network": "2001:19f0:7000:8945::",
"v6_main_ip": "2001:19f0:7000:8945::64",
"v6_network_size": "64",
"label": "Freetoo",
"internal_ip": "",
"kvm_url": "https://my.vultr.com/subs/vps/novnc/api.php?data=",
"auto_backups": "yes"
},
"1685960": {
"SUBID": "1685960",
"os": "FreeBSD 10 x64",
"ram": "768 MB",
"disk": "Virtual 15 GB",
"main_ip": "108.61.190.64",
"vcpu_count": "1",
"location": "Frankfurt",
"DCID": "9",
"default_password": "1",
"date_created": "2015-02-09 00:22:42",
"pending_charges": 2.54,
"status": "active",
"cost_per_month": "6.00",
"current_bandwidth_gb": 0.612,
"allowed_bandwidth_gb": "1000",
"netmask_v4": "255.255.255.0",
"gateway_v4": "108.61.190.1",
"power_status": "running",
"VPSPLANID": "29",
"v6_network": "2001:19f0:6c00:8141::",
"v6_main_ip": "2001:19f0:6c00:8141::64",
"v6_network_size": "64",
"label": "",
"internal_ip": "",
"kvm_url": "https://my.vultr.com/subs/vps/novnc/api.php?data=",
"auto_backups": "yes"
},
"1694100": {
"SUBID": "1694100",
"os": "FreeBSD 10 x64",
"ram": "768 MB",
"disk": "Virtual 15 GB",
"main_ip": "108.61.175.20",
"vcpu_count": "1",
"location": "London",
"DCID": "8",
"default_password": "9",
"date_created": "2015-02-12 13:21:33",
"pending_charges": 2.54,
"status": "active",
"cost_per_month": "6.00",
"current_bandwidth_gb": 1.51,
"allowed_bandwidth_gb": "1000",
"netmask_v4": "255.255.255.0",
"gateway_v4": "108.61.175.1",
"power_status": "running",
"VPSPLANID": "29",
"v6_network": "2001:19f0:7400:84c6::",
"v6_main_ip": "2001:19f0:7400:84c6::64",
"v6_network_size": "64",
"label": "",
"internal_ip": "",
"kvm_url": "https://my.vultr.com/subs/vps/novnc/api.php?data=",
"auto_backups": "yes"
},
"1847630": {
"SUBID": "1847630",
"os": "FreeBSD 10 x64",
"ram": "768 MB",
"disk": "Virtual 15 GB",
"main_ip": "108.61.169.203",
"vcpu_count": "1",
"location": "Sydney",
"DCID": "19",
"default_password": "ye!5",
"date_created": "2015-04-12 05:57:47",
"pending_charges": 0.11,
"status": "active",
"cost_per_month": "5.00",
"current_bandwidth_gb": 2.43,
"allowed_bandwidth_gb": "200",
"netmask_v4": "255.255.254.0",
"gateway_v4": "108.61.168.1",
"power_status": "stopped",
"VPSPLANID": "31",
"v6_network": "2001:19f0:5800:8561::",
"v6_main_ip": "2001:19f0:5800:8561::64",
"v6_network_size": "64",
"label": "sydney temp",
"internal_ip": "",
"kvm_url": "https://my.vultr.com/subs/vps/novnc/api.php?data=",
"auto_backups": "no"
}
}
Code:
function getlist(){
$list_output = file_get_contents('https://api.vultr.com/v1/server/list?api_key=UY');
return $list_output;
}
//var_dump($server_output);
echo '<br><br><br><br>';
$output = getlist();
$decoded = json_decode($output, true);
//var_dump($decoded);
foreach ($decoded as $value) {
//echo $value['SUBID'];
foreach ($value['SUBID'] as $piece) {
echo '<br>';
//var_dump($value);
echo $piece;
}
}
but any attempt to reach that second layer array fails with;
Warning: Invalid argument supplied for foreach() in /home/comm/www/mkdomain/vultr-mkvps.php on line 14
or similar.
How do I access the field 'labels' n the json viewer above and pattern match for Freetoo?
That is the exact object I am trying to reach.
No, once inside the foreach there is no more depth to iterate, its just strings after that (based on the dump), its not iterable anymore, so that foreach inside is useless. Just access the strings indices and make your desired condition:
foreach($decoded as $value) {
$id = $value['SUBID']; // string not array
$label = $value['label']; // string
if($label === 'Freetoo') {
// do something
echo $id; // and others that you have to do
}
}
Sample Output
If you're insistent of having another superfluous foreach inside, point to the current batch array, not the string.
foreach($decoded as $value) {
foreach($value as $key => $piece) { // point to `$value` the array, not `$value['SUBID']` (string)
if($key === 'label' && $piece === 'Freetoo') {
echo $value['SUBID'];
}
}
}
I hope this is you want..sample code
$output = json_decode($jsoninput,true);
foreach($output as $subid=>$row){
echo $subid;
foreach ($row as $piece) {
echo '<br>';
//var_dump($row);
echo $piece;
}
}
php to connect and get all rows
$query = 'SELECT * FROM cdr';
$sql = $remotedbh->prepare($query);
$sql->execute();
$dblist = $sql->fetchAll(PDO::FETCH_ASSOC);
if($sql->rowCount() > 0){
header('Content-type: application/json');
echo json_encode($dblist,JSON_FORCE_OBJECT);
}
else {
echo 0;
}
The problem is my json looks like this
{
"0": {
"calldate": "2013-08-14 11:41:28",
"clid": "\"tet\" <1002>",
"src": "1002",
"dst": "8834404",
"dcontext": "from-internal",
"channel": "SIP\/1002-00000000",
"dstchannel": "IAX2\/voipms-6749",
"lastapp": "Dial",
"lastdata": "IAX2\/voipms\/14798834404,300,",
"duration": "7",
"billsec": "0",
"disposition": "NO ANSWER",
"amaflags": "3",
"accountcode": "",
"uniqueid": "1376498488.1",
"userfield": "",
"did": "",
"recordingfile": "",
"cnum": "",
"cnam": "",
"outbound_cnum": "",
"outbound_cnam": "",
"dst_cnam": ""
},
"1": {
"calldate": "2013-08-14 11:42:55",
"clid": "\"Rtest\" <1002>",
"src": "1002",
"dst": "9187755592",
"dcontext": "from-internal",
"channel": "SIP\/1002-00000001",
"dstchannel": "IAX2\/voipms-121",
"lastapp": "Dial",
"lastdata": "IAX2\/voipms\/19187755592,300,",
"duration": "494",
"billsec": "485",
"disposition": "ANSWERED",
"amaflags": "3",
"accountcode": "",
"uniqueid": "1376498575.3",
"userfield": "",
"did": "",
"recordingfile": "",
"cnum": "",
"cnam": "",
"outbound_cnum": "",
"outbound_cnam": "",
"dst_cnam": ""
},
"2": {
so on so forth
I also am having the problem of everytime it pulls all the information a row is only half complete so it has a problem with that aswell, I was thinking of finding away to query the everything that is 5 minutes or older.
It's including the row numbers as you're using JSON_FORCE_OBJECT
Remove it and it it'll successfully return as an array.
e.g.
echo json_encode($dblist);
JSON_FORCE_OBJECT option in json_encode() forces the array to a json object with its indexes as keys. Removing that might get working for you.
update :
because while testing with a sample array
$test = array(array("calldate"=> "2013-08-14","src"=> "1002"),
array("calldate"=> "2013-08-18","src"=> "1003")
);
echo json_encode($test,JSON_FORCE_OBJECT);
//Outputs :
//{"0":{"calldate":"2013-08-14","src":"1002"},"1":{"calldate":"2013-08-18","src":"1003"}}
and
echo json_encode($test);
//Outputs :
// Gave me [{"calldate":"2013-08-14","src":"1002"},{"calldate":"2013-08-18","src":"1003"}]
so using just
echo json_encode($dblist);
should do the trick
I have one array images from Json:
images=JSON.decode(images);
This is the array value :
[
{
"title": "",
"description": "",
"name": "loc commerciale.jpg"
},
{
"title": "",
"description": "",
"name": "foto2.jpg"
},
{
"title": "",
"description": "",
"name": "foto 1.jpg"
},
{
"title": "",
"description": "",
"name": "a01.jpg"
}
]
I get the value from name :
images.each(function(image){
alert(image.name);
});
I need to get only the first value name
Like php :
$images = (array) json_decode($row->images);
$first = true;
foreach ($images as $k => $image) {
if ($first)
{
$firstimage= $image->name;
$first = false;
}
}
Try:
if (images[0].length){
var firstImageName = images[0].name;
}