Parsing SimpleXML Object data - php

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

Related

get std class value from an std classin php

stdClass Object
(
[id_pro_alert] => 155
[User_Id] => 252
[Pro_Id] => 329
[alertmethod] => daily
[Alertname] => xcxv
[name] => cyriac
[email] => cyriac#tewve.com
[date] => 2016-21-10 09:20:26
[mobile] =>
[comments] =>
[Alert_Id] => 329
[Prop_Purpose] => lease
[Min_Area] => 500
[Max_Area] => 1000
[Area_unit] => Sq.ft
[Min_cost] => 1000
[Max_cost] => 10000
[City] => kochi
[Create_Date] => 2016-10-17 12:59:14
[Update_Date] => 2016-10-17 12:59:14
[Status] => Active
[0] => stdClass Object
(
[Prop_type] => Agricultural Land
)
[1] => stdClass Object
(
[Prop_type] => Office in IT park
)
[2] => stdClass Object
(
[Prop_type] => Business center
)
)
How to get Prop_type value from stdclass
Check this, You can access all Prop_type's
foreach($data as $key=>$row){
if (is_int($key)) {
echo $row->Prop_type;
}
}
Create array of Prop_type's
$propData =array();
foreach($data as $key=>$row){
if (is_int($key)) {
$propData[] = $row->Prop_type;
}
}
echo $array->0->Prop_type;

How to split array data returned from json string in php

I have json return string like given below. I want to extract cancellation Policy list of objects like cutoff Time and refund In Percentage. I tried using for-loop but it didn't help me. Can you please help me on extracting this.
Array (
[apiStatus] => Array ( [success] => 1 [message] => SUCCESS ) <br>
[apiAvailableBuses] => Array ( <br>
[0] => Array ( [droppingPoints] => [availableSeats] => 41 <br>[partialCancellationAllowed] => [arrivalTime] => 08:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:00PM [location] => Ameerpet,|Jeans Corner 9687452130 [id] => 6 ) [1] => Array ( [time] => 09:15PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 09:10PM [location] => Kondapur,Toyota Show room [id] => 2244 ) ) [operatorName] => Deepak Travels [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6622 [fare] => 800 [busType] => 2+1 Hi-Tech Non A/c [routeScheduleId] => 6622 [commPCT] => 0 [operatorId] => 213 [inventoryType] => 0 ) <br>
[1] => Array ( [droppingPoints] => [availableSeats] => 41 [partialCancellationAllowed] => [arrivalTime] => 07:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:10PM [location] => Ameerpet,|Jeans Corner [id] => 6 ) [1] => Array ( [time] => 09:00PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 08:30PM [location] => KUKATPALLY,JNTU [id] => 2230 ) ) [operatorName] => Dhanunjayabus [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6743 [fare] => 900 [busType] => VOLVO [routeScheduleId] => 6743 [commPCT] => 0 [operatorId] => 233 [inventoryType] => 0 )
)
)
Use a foreach() for it like so:
foreach ($your_response['apiAvailableBuses'] as $el) {
$cancellationPolicy[] = $el['cancellationPolicy'];
}
Try this:
foreach($data['apiStatus']['apiAvailableBuses'] as $item) {
foreach($item['cancellationPolicy'] as $key => $json) {
$jsonDecoded = json_decode($json, true);
// And you will have access to the data like this
// $jsonDecoded['cutoffTime'];
// $jsonDecoded['refundInPercentage'];
}
}
$response = json_decode($apiResponse);
$cancellationPolicies = [];
foreach ($response->apiAvailableBuses as $availableBus) {
$cancellationPolicies[] = $availableBus['cancellationPolicy'];
// if you want to display something you can simply do it like this;
echo $availableBus['cancellationPolicy']->cutoffTime;
}

Extracting data from simplexml_load_file not working

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

Handling JSON response from cURL

I am trying to get data from an address verification API I use, and I'm having trouble getting data from it. I have no problem cURLing the addresses and getting a response, but I need help with PHP handling the response.
JSON structure:
[
{ "input_index": 0,
"candidate_index": 0,
"addressee": "Apple Inc",
"delivery_line_1": "1 Infinite Loop",
"delivery_line_2": "PO Box 42",
"last_line": "Cupertino CA 95014-2083",
"delivery_point_barcode": "950142083017",
"metadata": {
"latitude":"48.12685",
"longitude":"-39.16847"
},
}
{ "input_index": 1,
"candidate_index": 0,
"addressee": "Google Inc",
"delivery_line_1": "1600 Amphitheater Pkwy",
"delivery_line_2": "",
"last_line": "Mountain View CA 94043-1351",
"delivery_point_barcode": "950142083017",
"metadata": {
"latitude":"48.12685",
"longitude":"-39.16847"
},
}
]
My code:
$response = curl_exec($ch);
curl_close($ch);
$rd = json_decode($response);
echo $rd->metadata[0]->latitude;
But then I get the error of Trying to get property of non-object.
What am I doing wrong?
EDIT:
print_r($rd); gives me:
Array ( [0] => stdClass Object ( [input_index] => 0 [candidate_index]
=> 0 [addressee] => Randolph Gray [delivery_line_1] => 8758 Sunset Breeze Dr [last_line] => Reno NV 89506-4136 [delivery_point_barcode]
=> 895064136585 [components] => stdClass Object ( [primary_number] => 8758 [street_name] => Sunset Breeze [street_suffix] => Dr [city_name]
=> Reno [state_abbreviation] => NV [zipcode] => 89506 [plus4_code] => 4136 [delivery_point] => 58 [delivery_point_check_digit] => 5 ) [metadata] => stdClass Object ( [record_type] => S [zip_type] => Standard [county_fips] => 32031 [county_name] => Washoe [carrier_route] => C038 [congressional_district] => 02 [rdi] => Residential [elot_sequence] => 0381 [elot_sort] => A [latitude] =>
39.63353 [longitude] => -119.89745 [precision] => Zip9 [time_zone] => Pacific [utc_offset] => -8 [dst] => 1 ) [analysis] => stdClass Object ( [dpv_match_code] => Y [dpv_footnotes] => AABB [dpv_cmra] => N [dpv_vacant] => N [active] => Y ) ) [1] => stdClass Object ( [input_index] => 1 [candidate_index] => 0 [addressee] => Julio Valdez [delivery_line_1] => 7464 Gannon Dr [last_line] => Reno NV 89506-3186 [delivery_point_barcode] => 895063186644 [components] => stdClass Object ( [primary_number] => 7464 [street_name] => Gannon [street_suffix] => Dr [city_name] => Reno [state_abbreviation] => NV [zipcode] => 89506 [plus4_code] => 3186 [delivery_point] => 64 [delivery_point_check_digit] => 4 ) [metadata] => stdClass Object ( [record_type] => S [zip_type] => Standard [county_fips] => 32031 [county_name] => Washoe [carrier_route] => C038 [congressional_district] => 02 [rdi] => Residential [elot_sequence] => 0048 [elot_sort] => A [latitude] => 39.62646 [longitude] => -119.89913 [precision] => Zip9 [time_zone] => Pacific [utc_offset] => -8 [dst] => 1 ) [analysis] => stdClass Object ( [dpv_match_code] => Y [dpv_footnotes] => AABB [dpv_cmra] => N [dpv_vacant] => N [active] => Y ) ) [2] => stdClass Object ( [input_index] => 2 [candidate_index] => 0 [addressee] => Nicholas Carone [delivery_line_1] => 8685 Bagpipe Cir [last_line] => Reno NV 89506-4165 [delivery_point_barcode] => 895064165853 [components] => stdClass Object ( [primary_number] => 8685 [street_name] => Bagpipe [street_suffix] => Cir [city_name] => Reno [state_abbreviation] => NV [zipcode] => 89506 [plus4_code] => 4165 [delivery_point] => 85 [delivery_point_check_digit] => 3 ) [metadata] => stdClass Object ( [record_type] => S [zip_type] => Standard [county_fips] => 32031 [county_name] => Washoe [carrier_route] => C038 [congressional_district] => 02 [rdi] => Residential [elot_sequence] => 0227 [elot_sort] => A [latitude] =>
39.63367 [longitude] => -119.89965 [precision] => Zip9 [time_zone] => Pacific [utc_offset] => -8 [dst] => 1 ) [analysis] => stdClass Object ( [dpv_match_code] => Y [dpv_footnotes] => AABB [dpv_cmra] => N [dpv_vacant] => N [active] => Y ) ) )
Invalid JSON:
"metadata": {
"latitude":"48.12685",
"longitude":"-39.16847
} ...
should be:
"metadata": {
"latitude":"48.12685",
"longitude":"-39.16847"
} ...
Mind the closing " on the longitude value.
furthermore, the two entries need to be separated by ,:
[
{ "input_index": 0,
...
},
{ "input_index": 1,
...
}
]
finally: what you get is an array of objects - not an object with arrays:
$rd[0]->metadata->latitude ...

displaying array values with simplexml_load_string

I need to get some data from a xml output:
[current_condition] => SimpleXMLElement Object
(
[observation_time] => 12:22 PM
[temp_C] => 18
[temp_F] => 64
[weatherCode] => 116
[weatherIconUrl] => SimpleXMLElement Object
(
)
[weatherDesc] => SimpleXMLElement Object
(
)
[windspeedMiles] => 4
[windspeedKmph] => 7
[winddirDegree] => 180
[winddir16Point] => S
[precipMM] => 0.1
[humidity] => 52
[visibility] => 10
[pressure] => 1023
[cloudcover] => 50
)
[weather] => Array
(
[0] => SimpleXMLElement Object
(
[date] => 2013-04-23
[tempMaxC] => 20
[tempMaxF] => 69
[tempMinC] => 7
[tempMinF] => 44
[windspeedMiles] => 5
[windspeedKmph] => 8
[winddirection] => SSW
[winddir16Point] => SSW
[winddirDegree] => 210
[weatherCode] => 113
[weatherIconUrl] => SimpleXMLElement Object
(
)
[weatherDesc] => SimpleXMLElement Object
(
)
[precipMM] => 0.7
)
[1] => SimpleXMLElement Object
(
[date] => 2013-04-24
[tempMaxC] => 25
[tempMaxF] => 76
[tempMinC] => 8
[tempMinF] => 46
[windspeedMiles] => 3
[windspeedKmph] => 5
[winddirection] => NNE
[winddir16Point] => NNE
[winddirDegree] => 24
[weatherCode] => 113
[weatherIconUrl] => SimpleXMLElement Object
(
)
[weatherDesc] => SimpleXMLElement Object
(
)
[precipMM] => 0.3
)
)
Im using
printf("<p>Current temperature %s and code %s</p>",
$xml->current_condition->temp_C, $xml->current_condition->weatherCode);
to output the temperature and the weather code, and is working fine, is outputing:
Current temperature 18 and code 116
Now how can I TempMaxC and TempMinC from Weather Array [0]
and also from array [1]
Thanks
You can use a foreach:
foreach($xml->weather as $weatherObj) {
echo "<h2>Weather on {$weatherObj->date}</h2>";
echo "<ul>";
echo "<li>Max temp: {$weatherObj->tempMaxC}</li>";
echo "<li>Min temp: {$weatherObj->tempMinC}</li>";
echo "</ul>";
}

Categories