I am trying to read XML attributes from XML file. I want to echo baadNavn.
<?php
$url = "https://xml.websejler.dk/da/baad/1234";
$xml = simplexml_load_file($url);
print_r($xml);
echo $xml[baad][baadNavn];
?>
What do I wrong?
Print_r gives me:
SimpleXMLElement Object ( [baad] => SimpleXMLElement Object ( [#attributes] => Array ( [baadId] => 1234 [maalerId] => 32217 [baadNavn] => Ongo Bongo [baadStatus] => dhkolbaad [dhKlasseStatus] => skrogmedspeciel [nation] => DEN [sejlnummer] => 46 [byggerNavn] => Granada Yacht [byggeAar] => 1978 [maaleDato] => 1991-05-13T00:00:00 [stabgodk] => 0 [skrogMaterialeId] => 1003 [materiale] => GRP [opfolg] => 0 [fysisk] => 1 [baadtypeId] => 146 [rigsejlId] => 28158 [skrogId] => 17214 [specielId] => 79368 ) [certifikat] => SimpleXMLElement Object ( [#attributes] => Array ( [certifikatId] => 1234 [gyldigt] => 0 ) ) [baadtype] => SimpleXMLElement Object ( [#attributes] => Array ( [baadtypeId] => 146 [baadtypeNavn] => GRANADA 31 [baadStatus] => dhkolbaad [dhKlasseStatus] => skrogmedspeciel [dhBeregnes] => 1 [bem] => Granada 311 har samme skrog som Granada 31. De første ca. 35 var med blykøl (KC 0,96) - senere kommer det med jernkøl (KC 1,17) [skrogId] => 17214 [specielId] => 79368 ) ) [rigsejl] => SimpleXMLElement Object ( [#attributes] => Array ( [RigsejlId] => 28158 [E] => 3.27 [P] => 11.14 [HB] => 0.15 [MGM] => 2.10 [MGU] => 1.21 [Tmax] => 12.10 [LP] => 5.23 [FSP] => 0.08 [SPL] => 0.00 [J] => 3.49 [TPS] => 0.00 [JHW] => 0.00 [ISP] => 12.38 [SL] => 0.00 [SLU] => 0.00 [SLE] => 0.00 [SF] => 0.00 [SMG] => 0.00 [SFA] => 0.00 [SMGA] => 0.00 [PropelId] => 2 [propel] => Fri foldepropel med 2-3 blade (2) [RF] => 0 [MF] => 0 [HF] => 0 ) ) [skrog] => SimpleXMLElement Object ( [#attributes] => Array ( [SkrogId] => 17214 [Gmax] => 6.42 [SGmax] => 5.59 [FBSB] => 0.93 [FBBB] => 0.94 [SBmax] => 5.73 [UDFSB] => 0.26 [UDFBB] => 0.26 [OF] => 1.17 [OA] => 0.00 [UDHBmax] => 0.00 [UDHmax] => 0.00 [STF] => 1.11 [AF] => 0.00 ) ) [speciel] => SimpleXMLElement Object ( [#attributes] => Array ( [SpecielId] => 79368 [Bmax] => 3.05 [LOA] => 9.38 [D] => 4.17 [K] => 1.80 [KC] => 0.96 [KFId] => 1 [KF] => Normal [KontrolVejet] => 0 [KontrolMaalt] => 0 [KontrolKrenget] => 0 ) ) [ejer] => SimpleXMLElement Object ( [#attributes] => Array ( [personId] => 53371 [klubId] => 318 [klubNavn] => Aarhus Sejlklub [arrangor] => 1 ) ) [offentligmaaler] => SimpleXMLElement Object ( [#attributes] => Array ( [personId] => 32217 [aktiv] => 0 [maaHentePersonlister] => 0 [offentlig] => 0 [sejlmager] => 0 [maalerbem] => [navn] => Niels Agerskov ) ) [beregning] => SimpleXMLElement Object ( [#attributes] => Array ( [baadId] => 1234 [status] => beregnet [oprettetTid] => 2019-05-10T12:15:32.637 [beregnetTid] => 2019-05-10T12:16:31.447 [beregnetOATid] => 43595.5115 [beskedSendes] => 1 ) ) ) )
XML files contains:
<websejler>
<baad baadId="1234" maalerId="32217" baadNavn="Ongo Bongo" baadStatus="dhkolbaad" dhKlasseStatus="skrogmedspeciel" nation="DEN" sejlnummer="46" byggerNavn="Granada Yacht" byggeAar="1978" maaleDato="1991-05-13T00:00:00" stabgodk="0" skrogMaterialeId="1003" materiale="GRP" opfolg="0" fysisk="1" baadtypeId="146" rigsejlId="28158" skrogId="17214" specielId="79368">
<certifikat certifikatId="1234" gyldigt="0"/>
<baadtype baadtypeId="146" baadtypeNavn="GRANADA 31" baadStatus="dhkolbaad" dhKlasseStatus="skrogmedspeciel" dhBeregnes="1" bem="Granada 311 har samme skrog som Granada 31. De første ca. 35 var med blykøl (KC 0,96) - senere kommer det med jernkøl (KC 1,17)" skrogId="17214" specielId="79368"/>
<rigsejl RigsejlId="28158" E="3.27" P="11.14" HB="0.15" MGM="2.10" MGU="1.21" Tmax="12.10" LP="5.23" FSP="0.08" SPL="0.00" J="3.49" TPS="0.00" JHW="0.00" ISP="12.38" SL="0.00" SLU="0.00" SLE="0.00" SF="0.00" SMG="0.00" SFA="0.00" SMGA="0.00" PropelId="2" propel="Fri foldepropel med 2-3 blade (2)" RF="0" MF="0" HF="0"/>
<skrog SkrogId="17214" Gmax="6.42" SGmax="5.59" FBSB="0.93" FBBB="0.94" SBmax="5.73" UDFSB="0.26" UDFBB="0.26" OF="1.17" OA="0.00" UDHBmax="0.00" UDHmax="0.00" STF="1.11" AF="0.00"/>
<speciel SpecielId="79368" Bmax="3.05" LOA="9.38" D="4.17" K="1.80" KC="0.96" KFId="1" KF="Normal" KontrolVejet="0" KontrolMaalt="0" KontrolKrenget="0"/>
<ejer personId="53371" klubId="318" klubNavn="Aarhus Sejlklub" arrangor="1"/>
<offentligmaaler personId="32217" aktiv="0" maaHentePersonlister="0" offentlig="0" sejlmager="0" maalerbem="" navn="Niels Agerskov"/>
<beregning baadId="1234" status="beregnet" oprettetTid="2019-05-10T12:15:32.637" beregnetTid="2019-05-10T12:16:31.447" beregnetOATid="43595.5115" beskedSendes="1"/>
</baad>
</websejler>
I expect to get "Ongo Bongo" as result.
$url = "https://xml.websejler.dk/da/baad/1234";
$xml = simplexml_load_file($url);
echo (string) $xml->baad->attributes()['baadNavn']; // Ongo Bongo
You can use the attributes() function on the node to get it's attributes:
$xml_str = '<xml>
<node>
<someTag cp="c2">content</someTag>
</node>
</xml>';
$res = simplexml_load_string($xml_str);
$items = $res->xpath("//someTag");
var_dump((string) $items[0]->attributes()->cp);
The returned element is an SimpleXMLElement, so in order to use it I converted it to string (using the (string) cast).
Related
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);
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;
}
I query db and I have an array. How can I access stdClass object ? And I want also serializedName property like in java serializedName. So, The fields which query from db must be assign with my custom object class fields.How can I use this?
Array
(
[0] => stdClass Object
(
[receipt_id] => 1
[defect] => asd
[tec_report] => sad
[doc_number] => asd
[warrant] => 12
[warrant_start] => 2016-01-05
[warrant_end] => 2016-01-29
[repair_time] => 3
[receipt_date] => 2016-01-05
[delivery_date] =>
[service_type_id] => 0
[service_price] => 0
[part_price] => 0
[pay_type] =>
[labour] => 0
[summary] => 0
[technician_id] =>
[customer_id] => 0
[device_id] => 0
[seri_number] =>
)
[1] => stdClass Object
(
[receipt_id] => 2
[defect] => asdsad
[tec_report] => asds
[doc_number] =>
[warrant] =>
[warrant_start] =>
[warrant_end] =>
[repair_time] =>
[receipt_date] => 2016-01-05
[delivery_date] =>
[service_type_id] => 1
[service_price] => 12
[part_price] => 12
[pay_type] =>
[labour] => 12
[summary] => 12
[technician_id] =>
[customer_id] => 21
[device_id] => 12
[seri_number] =>
)
)
try this for one by one
echo $array[0]->receipt_id;
try this :
foreach($yourArray as $val){
echo $val->receipt_id;
echo "<br/>".$val->defect;
}
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
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>";
}