I'm trying to use the stackoverflow API and I want to get answers of a question in a php array. So far here is my php code:
<?php
//KEY
$string = "key=my_key";
//Call stack API .$string
$stack_url = "compress.zlib://http://api.stackoverflow.com/1.1/questions";
//Get and Store API results into a variable
$result = file_get_contents($stack_url);
$jsonArray = json_decode($result);
print_r($jsonArray);
//echo($jsonArray->questions[0]->question_answers_url);
//var_dump($jsonArray);
?>
I want to store the answers of a question in an array called answers so that I can access them with a for loop.
The answer i get is :
stdClass Object
(
[total] => 2618591
[page] => 1
[pagesize] => 30
[questions] => Array
(
[0] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => ssh
[2] => openssh
[3] => rsacryptoserviceprovider
)
[answer_count] => 1
[favorite_count] => 0
[question_timeline_url] => /questions/9164203/timeline
[question_comments_url] => /questions/9164203/comments
[question_answers_url] => /questions/9164203/answers
[question_id] => 9164203
[owner] => stdClass Object
(
[user_id] => 311966
[user_type] => registered
[display_name] => simonc
[reputation] => 301
[email_hash] => 021f3344004f0c886d715314fa02037d
)
[creation_date] => 1328548627
[last_edit_date] => 1328611688
[last_activity_date] => 1328611688
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 25
[score] => 0
[community_owned] =>
[title] => Format of PKCS private keys
)
[1] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => .net
[2] => combobox
)
[answer_count] => 3
[favorite_count] => 0
[question_timeline_url] => /questions/9174765/timeline
[question_comments_url] => /questions/9174765/comments
[question_answers_url] => /questions/9174765/answers
[question_id] => 9174765
[owner] => stdClass Object
(
[user_id] => 1194399
[user_type] => registered
[display_name] => Goxy
[reputation] => 1
[email_hash] => 5fc8c96b6b85c6339cb9ac4ab60cb247
)
[creation_date] => 1328611202
[last_activity_date] => 1328611686
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 15
[score] => 0
[community_owned] =>
[title] => WPF: Bind simple List<myClass> to Combobox
)
....
Not sure exactly which property you want to extract, but I assume it's the 'question_answers_url'.
$answersArray = Array();
for($i=0;$i<count($jsonArray['questions']);$i++){
//assuming it is the 'question_answers_url' property that you want
array_push($answersArray,$jsonArray['questions'][$i]['question_answers_url']);
}
Ought to do it.
Related
I have an object $myObject; I'm trying to return php object as json, but it loses some data. This is how $myObject looks:
CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList Object
(
[priceListId:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 32
[amounts:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[0] => 1000
[1] => 2000
[2] => 3000
[3] => 4000
[4] => 5000
[5] => 6000
[6] => 7000
)
[amountsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[1000] => 0
[2000] => 1
[3000] => 2
[4000] => 3
[5000] => 4
[6000] => 5
[7000] => 6
)
[periods:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[0] => 10
[1] => 15
[2] => 20
[3] => 25
[4] => 30
)
[periodsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[10] => 0
[15] => 1
[20] => 2
[25] => 3
[30] => 4
)
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 7000
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 30
[prices:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[30] => Array
(
[7000] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price Object
(
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 30
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 7000
[charge:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1580
[interest:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[administrativeFee:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[payment:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[annualPercentageRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1089.6
[annualInterestRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 274.62
[schedule:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] =>
)
)
)
[settings:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings Object
(
[mode:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => credits
[preset:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] =>
[implementation:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => matrix
[defaults:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => Array
(
[period] =>
[amount] =>
)
)
)
After json_encode($myObject); new data looks like this (screenshot for better json view):
screenshot of returned json
Why information I wrote below is missing and how to access it?
Missing stuff:
[7000] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price Object
(
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 30
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 7000
[charge:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1580
[interest:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[administrativeFee:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[payment:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[annualPercentageRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1089.6
[annualInterestRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 274.62
[schedule:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] =>
)
The problem is json_encode can not access private properties.
Here are some workarounds you could do:
Convert the properties to be public
You could use a reflection class to convert the properties accessibility before you convert it
Example:
$refObject = new ReflectionObject( $obj );
$refProperty = $refObject->getProperty( 'property' );
$refProperty->setAccessible( true );
You could loop through the properties of the object using a Reflection object and call all the getters converting the object into an array structure that could be easily translated
Refelection Class Documentation
I've that xml structure retrieving from device
<packet>
<info action="fiscalmemory" fiscalmemorysize="1048576" recordsize="464" fiscal="1" uniqueno="ABC12345678" nip="123-456-78-90" maxrecordscount="2144" recordscount="7" maxreportscount="1830" reportscount="4" resetmaxcount="200" resetcount="0" taxratesprglimit="30" taxratesprg="1" currencychangeprglimit="4" currencychangeprg="0" fiscalstartdate="dd-mm-yyyy hh:dd:ss" fiscalstopdate="dd-mm-yyyy hh:dd:ss" currencyname="PLN" />
<ptu name="A" bres="Nobi">123.23</ptu>
<ptu name="B">123.23</ptu>
<ptu name="D">8</ptu>
<sale>999.23</sale>
</packet>
simpleXml does't see ptu's attributes
$array = simplexml_load_string($xml);
print_r($array);
It prints
SimpleXMLElement Object
(
[info] => SimpleXMLElement Object
(
[#attributes] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[ptu] => Array
(
[0] => 123.23
[1] => 123.23
[2] => 8
)
[sale] => 999.23
)
As we can see ptu doesn't contain attributes :/
I also tried parse it with recursive function because children also may contain chilren but without success :/
Could anybody point to me why SimpleXML doesn't take ptu's attributes and also share any parsing function?
Thanks in advance.
edited
As regards Nigel Ren I made that function
function parseXMLtoArray($xml){
$x = simplexml_load_string($xml);
$result = [];
function parse($xml, &$res){
$res['name'] = $xml->getName();
$res['value'] = $xml->__toString();
foreach ($xml->attributes() as $k => $v){
$res['attr'][$k] = $v->__toString();
}
foreach($xml->children() as $child){
parse($child, $res['children'][]);
}
}
parse($x, $result);
return $result;
}
$resArray = parseXMLtoArray($rawXml);
print_r($resArray);
this returns such array
Array
(
[name] => packet
[value] =>
[attr] => Array
(
[crc] => BKJFKHKD54
)
[children] => Array
(
[0] => Array
(
[name] => info
[value] =>
[attr] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[1] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => A
)
)
[2] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => B
)
)
[3] => Array
(
[name] => ptu
[value] => 8
[attr] => Array
(
[name] => D
)
)
[4] => Array
(
[name] => sale
[value] => 999.23
)
)
)
Is this correct?
Thanks again Nigel
When loading with SimpleXML, using print_r() gives only an idea of the content and doesn't have the full content. If you want to see the full content then use ->asXML()...
$array = simplexml_load_string($xml);
echo $array->asXML();
To check the attributes of <ptu> element, (this just gives the first one)...
echo $array->ptu[0]['name'];
This uses ->ptu to get the <ptu> element and takes the first one [0] and then takes the name attribute using ['name'].
This question already has answers here:
How to convert XML into array in PHP?
(12 answers)
Closed 7 years ago.
I am working on property site. My requirement is to import property info with its images and amenities and store it in to database. I've an xml array and i want to convert it into php array. I've xml array like this:-
SimpleXMLElement Object
(
[Listing] => Array
(
[0] => SimpleXMLElement Object
(
[count] => 1
[Ad_Type] => Rent
[Unit_Type] => Office
[Unit_Model] => SimpleXMLElement Object
(
)
[Primary_View] => SimpleXMLElement Object
(
)
[Unit_Builtup_Area] => 7593.00
[No_of_Bathroom] => 2
[Property_Title] => Business Center / BANKS offices/ Call Centre Offices
[Web_Remarks] => SimpleXMLElement Object
(
)
[Emirate] => Dubai
[Community] => Sheikh Zayed Road
[Property_Name] => Millennium Plaza
[Property_Ref_No] => AMB-R-1142
[Listing_Agent] => Janette Ceniza
[Listing_Agent_Phone] => 0564843282
[Listing_Date] => 2015-03-26 4:53:51 pm
[Last_Updated] => 2015-07-29 1:44:23 pm
[Bedrooms] => SimpleXMLElement Object
(
)
[Listing_Agent_Email] => consult1#khalidalattar.com
[Price] => 1200000
[Frequency] => per year
[Unit_Reference_No] => AMB-R-1142
[No_of_Rooms] => SimpleXMLElement Object
(
)
[Latitude] => 25.062252
[Longitude] => 55.130672
[unit_measure] => Sq.Ft.
[Featured] => 0
[Images] => SimpleXMLElement Object
(
[image] => Array
(
[0] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_19-1605-6d8e8f3aa6e53b45154eac91e2109ba4.jpg
[1] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_35-1605-660a612b520978e1249c29b7fb591b45.jpg
[2] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_36-1605-01d394a6a096b9a0252b30a10fd59c13.jpg
[3] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_38-1605-80df60708c007c5a85721b89c97836d8.jpg
[4] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_38-1605-1f9ffdde85af52dfc6f3548264c34ce0.jpg
[5] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_44-1605-322badce946a4883abe602bf8c221a93.jpg
[6] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_44-1605-117288432442fd54dae0e68238f39537.jpg
[7] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_54-1605-914e38a1abe6418ea10885b94e4f26de.jpg
[8] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_55-1605-fc756a57f7280678b41b07340e3d1e60.jpg
[9] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_55-1605-53eb6e2277f1b19ee40a36660086a20e.jpg
[10] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_58_36-1605-9e54faba2c9f96e31646c0660f3f0153.jpg
)
)
[Facilities] => SimpleXMLElement Object
(
[facility] => Array
(
[0] => Built in wardrobes
[1] => Covered parking
[2] => Public parking
)
)
[company_name] => Amber Real Estate
[Web_Tour] => SimpleXMLElement Object
(
)
[Threesixty_Tour] => SimpleXMLElement Object
(
)
[Audio_Tour] => SimpleXMLElement Object
(
)
[Virtual_Tour] => SimpleXMLElement Object
(
)
[QR_Code] => SimpleXMLElement Object
(
)
[company_logo] => http://crm.propspace.com/application/views/pictures/logos/16051408971828.png
[Parking] => 2
[Strno] => SimpleXMLElement Object
(
)
[PreviewLink] => http://crm.propspace.com/preview/index/14273740230306248/1605/?l_id=1576257622628120
)
)
)
There are multiple entries like this. I'd given first entry for the referrence. For converting this xml to php array I've written the below code:-
function convert_xml($xml){
$arr = array();
foreach($xml->children() as $property){
if(count($property->children()) == 0){
$arr[$property->getName()] = strval($property);
}else{
$arr[$property->getName()][] = xml2array($property);
}
}
return $arr;
}
$xml_Arr = convert_xml($xml);
echo "<pre>"; print_r($xml_Arr); exit;
I m getting the result as php array given below.
Array
(
[Listing] => Array
(
[0] => Array
(
[count] => 1
[Ad_Type] => Rent
[Unit_Type] => Office
[Unit_Model] =>
[Primary_View] =>
[Unit_Builtup_Area] => 7593.00
[No_of_Bathroom] => 2
[Property_Title] => Business Center / BANKS offices/ Call Centre Offices
[Emirate] => Dubai
[Community] => Sheikh Zayed Road
[Property_Name] => Millennium Plaza
[Property_Ref_No] => AMB-R-1142
[Listing_Agent] => Janette Ceniza
[Listing_Agent_Phone] => 0564843282
[Listing_Date] => 2015-03-26 4:53:51 pm
[Last_Updated] => 2015-07-29 1:44:23 pm
[Bedrooms] =>
[Listing_Agent_Email] => consult1#khalidalattar.com
[Price] => 1200000
[Frequency] => per year
[Unit_Reference_No] => AMB-R-1142
[No_of_Rooms] =>
[Latitude] => 25.062252
[Longitude] => 55.130672
[unit_measure] => Sq.Ft.
[Featured] => 0
[Images] => Array
(
[0] => Array
(
[image] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_58_36-1605-9e54faba2c9f96e31646c0660f3f0153.jpg
)
)
[Facilities] => Array
(
[0] => Array
(
[facility] => Public parking
)
)
[company_name] => Amber Real Estate
[Web_Tour] =>
[Threesixty_Tour] =>
[Audio_Tour] =>
[Virtual_Tour] =>
[QR_Code] =>
[company_logo] => http://crm.propspace.com/application/views/pictures/logos/16051408971828.png
[Parking] => 2
[Strno] =>
[PreviewLink] => http://crm.propspace.com/preview/index/14273740230306248/1605/?l_id=1576257622628120
)
)
)
There are 10 element inside image array, but it is returning only the last image. I want image array as well in my result.
foreach($xml->children() as $key=>$property){
if(count($property->children()) == 0){
$arr[$property->getName()] = strval($property);
}else{
$arr[$property->getName()][$key] = xml2array($property);
}
}
First off, I'm new to PHP and coding in general, so this might be quite an obvious answer.
I'm currently working with the Strava API, and I'm trying to extract data from an Array/Object which is the result of the following API call:
$recentactivities = $api->get('athlete/activities', array('per_page' => 100));
which returns:
Array (
[1] => stdClass Object (
[id] => XXXX
[resource_state] => 2
[external_id] => XXXX
[upload_id] => XXXX
[athlete] => stdClass Object (
[id] => XXXX
[resource_state] => 1
)
[name] => Let\'s see if I can remember how to do this cycling malarkey...
[distance] => 11858.3
[moving_time] => 1812
[elapsed_time] => 2220
[total_elevation_gain] => 44
[type] => Ride
[start_date] => 2014-07-12T13:48:17Z
[start_date_local] => 2014-07-12T14:48:17Z
[timezone] => (
GMT+00:00
) Europe/London
[start_latlng] => Array (
[0] => XXXX
[1] => XXXX
)
[end_latlng] => Array (
[0] => XXXX
[1] => -XXXX
)
[location_city] => XXXX
[location_state] => England
[location_country] => United Kingdom
[start_latitude] => XXXX
[start_longitude] => XXXXX
[achievement_count] => 4
[kudos_count] => 1
[comment_count] => 0
[athlete_count] => 1
[photo_count] => 0
[map] => stdClass Object (
[id] => a164894160
[summary_polyline] => XXXX
[resource_state] => 2
)
[trainer] =>
[commute] =>
[manual] =>
[private] =>
[flagged] =>
[gear_id] => b739244
[average_speed] => 6.544
[max_speed] => 10.8
[average_cadence] => 55.2
[average_temp] => 29
[average_watts] => 99.3
[kilojoules] => 179.9
[device_watts] =>
[average_heartrate] => 191.2
[max_heartrate] => 200
[truncated] =>
[has_kudoed] =>
)
This repeats for the most recent activities.
I'm attempting to extract average_heartrate, which I can do for a single object using the following:
$recentactivities[1]->average_heartrate;
but I'd like to extract all instances of average_heartrate from the Array. I've tried to use a foreach statement, but to be honest, I have no idea where to start.
Any help would be much appreciated.
It's actually pretty simple you can indeed use a foreach loop:
foreach($myArray as $obj){
//$obj is an object so:
if(isset($obj->average_heartrate)){
echo $obj->average_heartrate;
}
}
With this code you iterate through your array with objects and save the wanted array within an array so you can work further with it.
$heartrateArray = array(); // create a new array
//iterate through it with an foreach
foreach($recentactivities as $activity){
// save the average_heartrate as a value under a new key in the array
$heartrateArray[] = $activity->average_heartrate;
}
I have the following array structure, this is the array passed in to $response
Array
(
[inbox] => Array
(
[0] => Array
(
[location] => 3
[ID] => 8ba84195fe79a89af1a4b5bd8c280621
[smsc_number] => +44******
[sent] => 2013-02-25 14:57:20
[coding] => Default GSM alphabet (no compression)
[remote_number] => +447****
[status] => Read
[body] => Yeppp
)
)
[outbox] => Array
(
[0] => Array
(
[location] => 2
[ID] => d22c4368fadd64e98fab64acb6b8fa34
[reference_number] => 1
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => *****
[status] => Sent
[body] => Test
)
[1] => Array
(
[location] => 0
[ID] => f0c05e8dd2578d16d73bf5dbcf2ec3e6
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => 0****
[status] => UnSent
[body] => fdgg ddfgfdg fd
)
[2] => Array
(
[location] => 1
[ID] => d7537acb1b3994ecc11369bac46c4bb6
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => 0****3
[status] => UnSent
[body] => fdgg ddfgfdg fd
)
)
)
I'm only interested in the body of the inbox array. I thought I could just do two loops to get this, or just do $response[0] but it doesn't seem to work. Heres what I have:
$response = $sms->Get();
foreach ($response[0] as $value) {
foreach ($response as $value1) {
echo($value1['body']);
}
}
I'm obviously doing something very stupid - Any help would be really appreciated
Try this
foreach ($response['inbox'] as $inb) {
echo($inb['body']); }