trying to access json results in php - php

Im trying to display some data im receiving from the cloudstack API. I can display some of the data I want when I use the JSON as objects, with the following code;
stdClass Object
(
[listvirtualmachinesresponse] => stdClass Object
(
[count] => 2
[virtualmachine] => Array
(
[0] => stdClass Object
(
[id] => bab03c9b-94e0-429f-906c-8853de306e9a
[name] => LinuxL1
[displayname] => LinuxL1
[account] => admin
[domainid] => a3121682-837b-11e3-964c-001372f94016
[domain] => ROOT
[created] => 2014-05-08T13:43:01+0200
[state] => Running
[haenable] =>
[zoneid] => 7a3ee2f0-540a-4232-8264-50a47a91001d
[zonename] => Amsterdam
[hostid] => 024b9ca2-4076-488e-ad13-86dfb7f2b766
[hostname] => ptvirt6
[templateid] => cf6abb42-574f-4840-886a-8662c5914166
[templatename] => CentOS 6.5
[templatedisplaytext] => good
[passwordenabled] =>
[isoid] => cf6abb42-574f-4840-886a-8662c5914166
[isoname] => CentOS 6.5
[isodisplaytext] => good
[serviceofferingid] => 4fc30c59-4600-44ed-b0bb-7fc48e795d90
[serviceofferingname] => L1
[cpunumber] => 1
[cpuspeed] => 1000
[memory] => 1024
[cpuused] => 0.02%
[networkkbsread] => 55
[networkkbswrite] => 1
[diskkbsread] => 1000680
[diskkbswrite] => 1301501
[diskioread] => 77192
[diskiowrite] => 8884
[guestosid] => a92508f4-837b-11e3-964c-001372f94016
[rootdeviceid] => 0
[rootdevicetype] => ROOT
[securitygroup] => Array
(
[0] => stdClass Object
(
[id] => edfe848c-837b-11e3-964c-001372f94016
[name] => default
[description] => Default Security Group
[account] => admin
[ingressrule] => Array
(
)
[egressrule] => Array
(
)
[tags] => Array
(
)
)
)
[nic] => Array
(
[0] => stdClass Object
(
[id] => bfaeb76d-7b5a-46b1-aaa7-7dd15e86bf2e
[networkid] => 83007a42-e4b7-4ea2-aa21- 20938ea3bc56
[networkname] => defaultGuestNetwork
[netmask] => 111.111.111.111
[gateway] => 111.111.111.111
[ipaddress] => 111.111.111.111
[isolationuri] => ec2://untagged
[broadcasturi] => vlan://untagged
[traffictype] => Guest
[type] => Shared
[isdefault] => 1
[macaddress] => 06:a5:24:00:00:0a
)
)
[hypervisor] => KVM
[instancename] => i-2-9-VM
[tags] => Array
(
)
[affinitygroup] => Array
(
)
[displayvm] => 1
[isdynamicallyscalable] =>
)
I can read the name / state from the list with a foreach loop
<?php
$api_content = file_get_contents("http://127.0.0.1:5950/client/api?command=listVirtualMachines&domainid=1&account=admin&response=json");
$api_data = json_decode($api_content);
$ap_machine = $api_data->listvirtualmachinesresponse->virtualmachine;
echo "<pre>";
print_r($api_data);
echo "</pre>";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table border="1" width="300">
<tr>
<td>Naam</td>
<td>Status</td>
<td>Ip Address</td>
<td>Health</td>
</tr>
<?php
echo "<tr>";
foreach($ap_machine as $item){
echo "<td>".$item->name."</td>";
echo "<td>".$item->state."</td>";
echo "<td>".$item->nic->ipaddress."</td>";
if($item->state == 'Running'){
echo '<td><img src="/600px-Approve_icon.svg.png" height="50" width="50"> </td>';
}
else{
echo '<td><img src="/fail.png" height="25" width="25"></td>';
}
echo "</tr>";
}
?>
I've read online to make an associative array from the json list, I did that aswell and didnt get a result.

In your PHP code you are accessing nice key as a normal element of json:
echo "<td>".$item->nic->ipaddress."</td>";
But, from your var_dump output I can see its of array type.
So, to access elements of nice array, you'l have to access it by specifying array index.
echo "<td>".$item->nic[0]->ipaddress."</td>";

Look dude
change
$api_data = json_decode($api_content);
to
$api_data = json_decode($api_content, TRUE);
this makes it an associative array
check http://www.php.net/manual/en/function.json-decode.php

Related

Convert Array to html table in php

I have an array generated by an API i use a cpanel hosting with php 5.6.
I tried a lot of combination but is not working
The array are generated by emag marketplace api.
The code looks like
Array
(
[isError] =>
[messages] => Array
(
)
[results] => Array
(
[0] => Array
(
[vendor_name] => WISE COMPUTER SRLD
[id] => 2003677675
[parent_id] =>
[date] => 2017-05-21 10:55:18
[payment_mode] => RAMBURS
[payment_mode_id] => 1
[delivery_mode] => CURIER RO
[observation] =>
[status] => 4
[payment_status] => 0
[customer] => Array
(
[id] => 994041
[mkt_id] => 994041
[name] => Cristina Manuela Dancas
[company] => Cristina Manuela Dancas
[gender] =>
[phone_1] => 0743073616
[phone_2] =>
[phone_3] =>
[registration_number] =>
[code] =>
[email] =>
[billing_name] =>
[billing_phone] =>
[billing_country] => RO
[billing_suburb] => Bucuresti
[billing_city] => Sectorul 1
[billing_locality_id] => 2
[billing_street] => Str. Aviator Sanatescu nr. 57, parter, Ap1
[billing_postal_code] =>
[shipping_country] => RO
[shipping_suburb] => Bucuresti
[shipping_city] => Sectorul 1
[shipping_locality_id] => 2
[shipping_postal_code] =>
[shipping_contact] => Cristina Manuela Dancas
[shipping_phone] => 0743073616
[created] => 2017-05-21 10:55:19
[modified] => 2017-05-21 10:56:21
[bank] =>
[iban] =>
[legal_entity] => 0
[fax] =>
[is_vat_payer] => 1
[liable_person] =>
[shipping_street] => Str. Aviator Sanatescu nr. 57, parter, Ap1
)
I what to use php to convert in a HTML table.
Need some help. If you need more information please leave a message.
This is my quick solution to make a HTML table from a PHP array.
The essence is although, that a two-dimensional array, makes into a table that makes sense. Your array seems to be more complex, so converting into a useful table will probably take a bit more effort.
$data = array( array("ID","Firstname","Lastname","Phone"),
array("1","John","Jenkins","+91375953"),
array("2","Eduard","Kenny","+7244277"),
array("3","Anita","Beaumont","+427427427"),
array("4","Wanda","Wade","+274274247"),
array("4","Sarah","Colon","+835835"),
);
echo '<table border="1">';
foreach($data as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</table>';

How to get data from foreach loop using below Array?

How to get the values from array? I am stucked in this. Anybody knows please help me. I am getting only main array's values.
[0] => stdClass Object
(
[id] => 68427249
[active] => 1
[name] => Three Way
[status] => open
[market_type_id] => 3896
[market_type_name] => Three Way
[market_type_order_number] => 1000
[event_id] => 8669447
[event_name] => Nuovo Campobasso Calcio vs Jesina Calcio
[line] =>
[scope] => full_event
[order_number] => 0
[selections] => Array
(
[0] => stdClass Object
(
[id] => 558087597
[name] => Nuovo Campobasso Calcio
[status] => ok
[odd] => 2.32
[lay_odd] => 1.0
[order_number] => 0
[line] =>
[market_subtype_id] => 293985
[market_subtype_code] => 11
[market_subtype_name] => Home
[market_subtype_order_number] => 0
)
[1] => stdClass Object
(
[id] => 558087568
[name] => Draw
[status] => ok
[odd] => 3.13
[lay_odd] => 1.0
[order_number] => 1
[line] =>
[market_subtype_id] => 293986
[market_subtype_code] => 10
[market_subtype_name] => Draw
[market_subtype_order_number] => 1
)
[2] => stdClass Object
(
[id] => 558087589
[name] => Jesina Calcio
[status] => ok
[odd] => 2.57
[lay_odd] => 1.0
[order_number] => 2
[line] =>
[market_subtype_id] => 293987
[market_subtype_code] => 12
[market_subtype_name] => Away
[market_subtype_order_number] => 2
)
)
)
my code
foreach($m as $ms)
{
echo '<tr><td>'.$ps->id.'</td><td>'.$ms->event_name.'</td><td>'.$ms['selections']->odd.'</td></tr>';
}
My code is not working to get values from [selections]. Please help me to get values.
It will be something like this to access the data of selections as its also array. So, you need to run loop for selections to get its value.
foreach ($array as $obj) {
echo $obj->name;
echo $obj->status;
if (is_array($obj->selections)) {
foreach ($obj->selections as $selection) {
echo $selection->name;
echo $selection->odd;
}
}
}
I hope it will help you.
You can access your object array values like this :
foreach ($objArr as $obj) {
echo '<tr><td>'.$obj->id.'</td><td>'.$obj->event_name.'</td>';
foreach ($obj->selections as $objS) {
echo '<td>'.$objS->odd.'</td>';
}
echo '</tr>';
}
<?php
$user = (Object)["name" => "Meraj","email"=> "merajsiddiqui#outlook.com", "education" => (Object)[
"school" => "JMI", "college" => "GGSIPU"]];
function printer($nested_object)
{
foreach ($nested_object as $property => $value) {
if (is_object($value)) {
printer($value);
} else {
echo $property."=".$value."\n";
}
}
}
printer($user);
Instead of echoing you can do as per your requirements;
//output
name=Meraj
email=merajsiddiqui#outlook.com
school=JMI
college=GGSIPU

PHP array output specific key and/or value

I want to grab specific values based on keys in my PHP array.
I am getting a whole bunch of unwanted syntax.
I am using this library for API calls to a Insightly CRM https://github.com/Insightly/insightly-php
Code:
<!DOCTYPE html>
<html>
<head>
<?php
echo "<h1>PHP Insightly Test</h1>";
require("insightly.php");
$i = new Insightly('apikey');
$contacts = $i->getContacts();
?>
<title></title>
</head>
<body>
<?php
$array = array();
foreach ($contacts as $contact)
{
$array[] = $contact;
}
print_r($array[1]);
?>
</body>
</html>
Webpage output as follows:
stdClass Object ( [CONTACT_ID] => 1234567 [SALUTATION] => [FIRST_NAME] => Frank [LAST_NAME] => Foster [BACKGROUND] => [IMAGE_URL] => http://dfvd [DEFAULT_LINKED_ORGANISATION] => [OWNER_USER_ID] => 343435 [DATE_CREATED_UTC] => 2015-11-22 21:46:25 [DATE_UPDATED_UTC] => 2015-11-22 21:52:19 [VISIBLE_TO] => EVERYONE [VISIBLE_TEAM_ID] => [VISIBLE_USER_IDS] => [CUSTOMFIELDS] => Array ( ) [ADDRESSES] => Array ( ) [CONTACTINFOS] => Array ( [0] => stdClass Object ( [CONTACT_INFO_ID] => 34353453 [TYPE] => EMAIL [SUBTYPE] => [LABEL] => Work [DETAIL] => email#email.com ) ) [DATES] => Array ( ) [TAGS] => Array ( ) [LINKS] => Array ( ) [CONTACTLINKS] => Array ( ) [EMAILLINKS] => Array ( ) )
I require individual values
e.g (first name / last name) - Frank Foster
I tried print_r($array[1]['FIRST_NAME']);? but had no luck. Wondering if I need to encode or decode? Unsure the answer to this.
Thanks.
You can echo FIRST_NAME using this Syntax:
echo $array[1]->FIRST_NAME;
Use should use "->" to access object properties.
print_r($array[1]->FIRST_NAME);

How to echo an array value

I am fairly new to PHP and I am writing a PHP function that grabs an object from SOAP.
I found a code to convert it to an array but I can't manage to echo any data.
The array from print_r
Array
(
[Status] => Array
(
[Code] => 0
[Message] => OK
)
[Order] => Array
(
[OrderNumber] => 9334543
[ExternalOrderNumber] =>
[OrderTime] => 2014-07-15T15:20:31+02:00
[PaymentMethod] => invoice
[PaymentStatus] => Paid
[ShipmentMethod] => Mypack
[DeliveryStatus] => Delivered
[Language] => sv
[Customer] => Array
(
[CustomerId] => 13556
[CustomerNumber] =>
[Username] => admin
[Approved] => 1
[OrgNumber] => 9309138445
[Company] =>
[VatNumber] =>
[FirstName] => Jane
[LastName] => Doe
[Address] => Gatan
[Address2] =>
[Zip] => 1230
[City] => Staden
[Country] => Sweden
[CountryCode] => SE
[PhoneDay] => 84848474
[PhoneNight] =>
[PhoneMobile] =>
[Email] => mail#msn.com
[NewsLetter] =>
[OrgType] => person
[OtherDelivAddress] =>
[DelivName] =>
[DelivAddress] =>
[DelivAddress2] =>
[DelivZip] =>
[DelivCity] =>
[DelivCountry] =>
[DelivCountryCode] =>
)
[Comment] =>
[Notes] => 9063025471 UK/MA
[CurrencyCode] => SEK
[ExchangeRate] => 1
[LanguagePath] => se
[FreightWithoutVat] => 0
[FreightWithVat] => 0
[FreightVatPercentage] => 25
[PayoptionFeeWithoutVat] => 0
[PayoptionFeeWithVat] => 0
[PayoptionFeeVatPercentage] => 25
[CodWithoutVat] => 0
[CodWithVat] => 0
[CodVatPercentage] => 0
[DiscountWithoutVat] => 0
[DiscountWithVat] => 0
[DiscountVat] => 0
[TotalWithoutVat] => 4388
[TotalWithVat] => 5485
[TotalVat] => 1097
[PayWithoutVat] =>
[AffiliateCode] =>
[AffiliateName] =>
[OrderField] => Array
(
[0] => Array
(
[Name] => external_ref
[Value] => 43445
)
[1] => Array
(
[Name] => webshopid
[Value] => 423
)
[2] => Array
(
[Name] => webshopname
[Value] => Manuell
)
)
)
)
Non working code
echo $array[1][0]
I have tried different combos of indexes. I know how to return the values from the soap object but if I could do it this way it would be easier. It should work shouldn't it?
$array[1] is the second index of the array. the key of this array us "Status", this array contains a code and message
i assume you want to echo the message, you can do that with the following
echo $array[1]["Status"]["Message"];
You should use $array['Status']['Code'] , $array['Status']['Message'], $array['Order']['OrderNumber'], $array['Order']['Customer']['CustomerId'] and so on to display your data. It's an associative array so you need to use string keys and not numbers
try
$array['Order']['Customer']['LastName']
is my best guess without losing my sanity in that one line.
But for us to be sure please post the print_r($array) output
There are some way I always do this:
print_r($array);
And the other way is
$array[0]['Order']['LastName']
Try to access the arrays elements with the string keys, not the integer ones you are using:
echo $array['Order']['Customer']['Address'];
Another way you could see what is going on is by iterating through the array, and print out the keys and values:
foreach ($array as $key => $value)
echo "Key=$key value=$value<br>";

How to fetch specific fields from array using file_get_contents

I want to fetch player fields:
e.g id,name,tag,plat etc
I have this type of data:
stdClass Object
(
[player] => stdClass Object
(
[id] => 179203896
[game] => bf4
[plat] => pc
[name] => HeLLTiMe
[tag] => DK
[dateCheck] => 1391437377733
[dateUpdate] => 1391437377733
[dateCreate] => 1386696304438
[lastDay] => 20140117
[country] =>
[countryName] =>
[rank] => stdClass Object
(
[nr] => 73
[imgLarge] => bf4/ranks/r73.png
[img] => r73
[name] => Chief Warrant Officer Five III
[needed] => 4920000
[next] => stdClass Object
(
[nr] => 74
[img] => r74
[name] => Chief Warrant Officer Five IV
[needed] => 5030000
[curr] => 5022060
[relNeeded] => 110000
[relCurr] => 102060
[relProg] => 92.781818181818
)
)
[score] => 5025100
[timePlayed] => 862027
[uId] => 2832659368608119092
[uName] => HeLLTiMe
[uGava] => 0b8b00021ebfb32414e5a6051c2c9a40
[udCreate] => 1328606863000
[blPlayer] => http://battlelog.battlefield.com/bf4/soldier/HeLLTiMe/stats/179203896/pc/
[blUser] => http://battlelog.battlefield.com/bf4/user/HeLLTiMe/
[editable] =>
[viewable] => 1
[adminable] =>
[linked] =>
)
[stats] => stdClass Object
(
[reset] => stdClass Object
(
[lastReset] => 0
[score] => 0
[timePlayed] => 0
[timePlayedSinceLastReset] => 0
[kills] => 0
[deaths] => 0
[shotsFired] => 0
[shotsHit] => 0
[numLosses] => 0
[numWins] => 0
)
How can I fetch this data?
Here is my code:
<?php
$url = "http://api.bf4stats.com/api/playerInfo?plat=pc&name=HeLLTiMe";
$json = file_get_contents($url);
$data = json_decode($json);
echo "<pre>";
print_r($data);
?>
to get the name you should do this:
echo $data->player->name;
You need this because you have a stdClass Object
You can also change the out to just a array, you have to change this:
$data = json_decode($json);
to this:
$data = json_decode($json, true);
When you make this chagne you can get the value by this:
echo $data['player']['name'];
Edit
Below you can see the example, this works for me with no error.
$url = "http://api.bf4stats.com/api/playerInfo?plat=pc&name=HeLLTiMe";
$json = file_get_contents($url);
echo 'Using stdClass Object option<br>';
$data = json_decode($json);
echo $data->player->name;
echo '<br><br>Using Array option<br>';
$data = json_decode($json, true);
echo $data['player']['name'];
exit;
$result = array();
$result['name'] = $data->Player->name
var_dump($result);
Not sure what do you mean by fetch the data as already fetched it but if you ask how to access the fields you can do it like this.
print_r($data->player->name);

Categories