Extracting data from simplexml_load_file not working - php

I'm stuck on getting a value from a xml file, I've decided to use simplexml as it makes life easier but atm its doing the opposite.
My xml file look something like this:
<?xml version="1.0"?>
<fslb server="12345">
<statistics>
<frontend-connections>145</frontend-connections>
<global-response-time-average>1899ms</global-response-time-average>
<ecm-blacklist-size>0</ecm-blacklist-size>
<backend-connections>0 of 0</backend-connections>
<global-max-response-time>6888ms</global-max-response-time>
<global-ecm-cache-size>2396</global-ecm-cache-size>
<global-queue-length>0</global-queue-length>
<global-sidless-poll-average>0.00</global-sidless-poll-average>
<actual-card-requests>0</actual-card-requests>
<sid-sidless-requests>75% [109]/24% [36]</sid-sidless-requests>
<invalidated-clients>0</invalidated-clients>
<global-queue-average>0.00</global-queue-average>
<global-max-sidless-polls>0</global-max-sidless-polls>
<average-requests-per-card>0.00</average-requests-per-card>
<global-cache-efficiency>0%</global-cache-efficiency>
<total-requests-received>102934</total-requests-received>
</statistics>
<active-users>
<user name="RS.DOS" unread-messages="0" ipaddress="xxxx" client="Mgcamd" loggedonsince="2014-08-18 06:01:03p" requests="338" period=" 8.53" sid="0695" service-name="INT" request-handling="Queued in GC (External)" hop-list="[0]: None" hash="DE:26" latency="1900" />
<user name="S9" unread-messages="0" ipaddress="xxxx" client="Mgcamd" loggedonsince="2014-08-18 06:01:03p" requests="263" period="10.97" sid="0174" service-name=" XD" request-handling="Queued in GC (External)" hop-list="[0]: None" hash="80:C0" latency="748" />
<user name="M1" unread-messages="0" ipaddress="174.93.86.83" client="Newcamd" loggedonsince="2014-08-18 06:01:03p" requests="12844" period=" 0.22" sid="0688" service-name="INT" request-handling="Global Cached CWs" hop-list="[0]: None" hash="4A:3F" latency="0" />
<user name="S9" unread-messages="0" ipaddress="xxxx" client="Mgcamd" loggedonsince="2014-08-18 06:01:03p" requests="300" period=" 9.61" sid="0650" service-name="INT" request-handling="Queued in GC (External)" hop-list="[0]: None" hash="8A:4C" latency="909" />
</active-users>
</fslb>
My end goal is to extract the data from one "user" line (or the statistics line) and output it to mysql so that its saved in my db. The outputting part seems pretty easy, however I can't even get the data to be extracted in the first place -.-. This is my php code:
ini_set("user_agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
ini_set("max_execution_time", 0);
ini_set("memory_limit", "10000M");
$file_xml = "users.xml";
if(!file_exists($file_xml))
{
exit('Failed to open');
}
$fslb = simplexml_load_file($file_xml, 'SimpleXMLElement',LIBXML_NOCDATA);
$json_string = json_encode($fslb);
$result_array = json_decode($json_string, TRUE);
//print_r($fslb);
echo('<p> Total number of connections: ');
echo $result_array->statistics[0]->{'frontend-connections'};
echo('</p>');
echo('<p> Global-response-time-average: ');
echo $result_array->statistics[0]->{'global-response-time-average'};
echo('</p>');
I've spent hours trying to figure out how I can extract some data but it just wont go!
SimpleXMLElement Object ( [#attributes] => Array ( [server] => 12345 ) [statistics] => SimpleXMLElement Object ( [frontend-connections] => 145 [global-response-time-average] => 1899ms [ecm-blacklist-size] => 0 [backend-connections] => 0 of 0 [global-max-response-time] => 6888ms [global-ecm-cache-size] => 2396 [global-queue-length] => 0 [global-sidless-poll-average] => 0.00 [actual-card-requests] => 0 [sid-sidless-requests] => 75% [109]/24% [36] [invalidated-clients] => 0 [global-queue-average] => 0.00 [global-max-sidless-polls] => 0 [average-requests-per-card] => 0.00 [global-cache-efficiency] => 0% [total-requests-received] => 102934 ) [active-users] => SimpleXMLElement Object ( [user] => Array ( [0] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => RS.DOS [unread-messages] => 0 [ipaddress] => xxxx [client] => Mgcamd [loggedonsince] => 2014-08-18 06:01:03p [requests] => 338 [period] => 8.53 [sid] => 0695 [service-name] => INT [request-handling] => Queued in GC (External) [hop-list] => [0]: None [hash] => DE:26 [latency] => 1900 ) ) [1] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => S9 [unread-messages] => 0 [ipaddress] => xxxx [client] => Mgcamd [loggedonsince] => 2014-08-18 06:01:03p [requests] => 263 [period] => 10.97 [sid] => 0174 [service-name] => XD [request-handling] => Queued in GC (External) [hop-list] => [0]: None [hash] => 80:C0 [latency] => 748 ) ) [2] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => M1 [unread-messages] => 0 [ipaddress] => 174.93.86.83 [client] => Newcamd [loggedonsince] => 2014-08-18 06:01:03p [requests] => 12844 [period] => 0.22 [sid] => 0688 [service-name] => INT [request-handling] => Global Cached CWs [hop-list] => [0]: None [hash] => 4A:3F [latency] => 0 ) ) [3] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => S9 [unread-messages] => 0 [ipaddress] => xxxx [client] => Mgcamd [loggedonsince] => 2014-08-18 06:01:03p [requests] => 300 [period] => 9.61 [sid] => 0650 [service-name] => INT [request-handling] => Queued in GC (External) [hop-list] => [0]: None [hash] => 8A:4C [latency] => 909 ) ) ) ) )

That works for me
var_dump((string)$fslb->statistics->{"frontend-connections"});
http://php.net/manual/en/simplexmlelement.tostring.php

Related

Parsing SimpleXML Object data

How to get "file_url" from this data?
Response can contain few objects, and how to parse it?
Code that I use:
<?php
$r34data = simplexml_load_file('https://rule34.xxx/index.php?page=dapi&s=post&q=index&tags=green_hair&limit=2');
print_r($r34data);
Response:
SimpleXMLElement Object ( [#attributes] => Array ( [count] => 69175 [offset] => 0 ) [post] => Array ( [0] => SimpleXMLElement Object ( [#attributes] => Array ( [height] => 2039 [score] => 1 [file_url] => https://wimg.rule34.xxx/images/3820/01e0a587f6e303c34669a4f79c994100.png [parent_id] => [sample_url] => https://rule34.xxx/samples/3820/sample_01e0a587f6e303c34669a4f79c994100.jpg [sample_width] => 850 [sample_height] => 667 [preview_url] => https://rule34.xxx/thumbnails/3820/thumbnail_01e0a587f6e303c34669a4f79c994100.jpg [rating] => e [tags] => 1boy 2girls annette_(fire_emblem) annette_fantine_dominic ass back back_view bare_back big_ass big_breasts blue_eyes blue_lingerie breasts_outside byleth_(fire_emblem) byleth_(fire_emblem)_(male) byleth_(male) ffm_threesome fingering fingering_partner fire_emblem fire_emblem:_three_houses french_kiss green_hair kissing light_blue_lingerie lingerie long_hair lysithea_(fire_emblem) lysithea_von_ordelia medium_breasts medium_hair nintendo nipples orange_hair pink_eyes purple_lingerie pussy pussy_juice pussy_juice_trail quan_ming sex threesome vaginal_penetration white_hair [id] => 4324333 [width] => 2600 [change] => 1608630074 [md5] => 01e0a587f6e303c34669a4f79c994100 [creator_id] => 503169 [has_children] => false [created_at] => Tue Dec 22 09:21:59 +0000 2020 [status] => active [source] => https://www.pixiv.net/en/artworks/86455582 [has_notes] => false [has_comments] => false [preview_width] => 150 [preview_height] => 117 ) ) [1] => SimpleXMLElement Object ( [#attributes] => Array ( [height] => 1600 [score] => 10 [file_url] => https://wimg.rule34.xxx/images/3820/4a88c87d1cb18928bcee85207bf1c61b.jpeg [parent_id] => [sample_url] => https://rule34.xxx/samples/3820/sample_4a88c87d1cb18928bcee85207bf1c61b.jpg [sample_width] => 850 [sample_height] => 618 [preview_url] => https://rule34.xxx/thumbnails/3820/thumbnail_4a88c87d1cb18928bcee85207bf1c61b.jpg [rating] => e [tags] => 1boy 1boy1girl 1girls all_fours anal anal_sex barefoot bent_over big_breasts christmas clothed_male_nude_female clothing cum cum_in_ass cum_inside cum_leaking doggy_style ejaculation ejaculation_while_penetrated faceless_male feet female female_focus forehead_protector green_hair hair_bun headband huge_breasts kneeling long_hair looking_at_viewer looking_back male multicolored_hair naked naruto naruto_(series) naruto_shippuden nude open_mouth orange_eyes orange_hair pakura penetration pussy santa_costume smile soles standing tied_hair toes two_tone_hair vagina [id] => 4324142 [width] => 2202 [change] => 1608622103 [md5] => 4a88c87d1cb18928bcee85207bf1c61b [creator_id] => 631992 [has_children] => false [created_at] => Tue Dec 22 07:28:01 +0000 2020 [status] => active [source] => [has_notes] => false [has_comments] => false [preview_width] => 150 [preview_height] => 108 ) ) ) )
Please help!
(don't ask why I parsing rule34)
Hi You can conver it to the array and work with is easy
libxml_use_internal_errors(TRUE);
$objXmlDocument = simplexml_load_file("https://rule34.xxx/index.php?page=dapi&s=post&q=index&tags=green_hair&limit=2");
if ($objXmlDocument === FALSE) {
echo "There were errors parsing the XML file.\n";
foreach(libxml_get_errors() as $error) {
echo $error->message;
}
exit;
}
$objJsonDocument = json_encode($objXmlDocument);
$arrOutput = json_decode($objJsonDocument, TRUE);
echo "<pre>";
print_r($arrOutput);

Parse XML to Array with SimpleXML

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'].

Extract data from Array/Object in PHP?

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;
}

Array inside array, only take incoming array

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']); }

Stackoverflow API getting answers in array PHP

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.

Categories