isimpledesign Posted December 22, 2010 Share Posted December 22, 2010 Hi Guys I have never reall worked with xml and im stuck. I am gathering data from a class. include "example/class.php"; $data = new Class; $request = $data->List_Accounts(); $res = $data->run_xml($request); echo "<pre>"; print_r($res); echo "</pre>"; Ok so this is the output i get from the print_r(); <pre><!--?xml version="1.0" encoding="utf-8"?--> <rpc request_id="43535"> <response code="0" text="OK"> <account datatype="list"> <name datatype="username">arf34</name> <type datatype="account_type">3</type> <descr datatype="string">Linux Virtual Hosting</descr> <server datatype="int">35</server> </account> <account datatype="list"> <name datatype="username">awecerfewve</name> <type datatype="account_type">3</type> <descr datatype="string">Linux Virtual Hosting</descr> <server datatype="int">34</server> </account> </response></rpc></pre> How could i them loop through this data and pull out certain types like username and account_type using a foreach loop???? Can anyone please help with this. Thanks Quote Link to comment https://forums.phpfreaks.com/topic/222381-looping-through-foreach-with-xml-data/ Share on other sites More sharing options...
PFMaBiSmAd Posted December 22, 2010 Share Posted December 22, 2010 It appears that your class returns the xml document in the $res variable. You should use an xml parser, such as simplexml to operate on the xml document as an object. You would then use something similar to the following - $xml = simplexml_load_string($res); // echo '<pre>',print_r($xml,true),'</pre>'; // examine the data echo "Request id: {$xml['request_id']}<br />"; // attribute echo "Code: {$xml->response['code']}, Text: {$xml->response['text']}<br /><br />"; // attributes foreach($xml->response->account as $node){ echo "Datatype: {$node['datatype']}<br />"; // attribute echo "Name: {$node->name}<br />"; // data echo "Type: {$node->type}<br />"; echo "Descr: {$node->descr}<br />"; echo "Server: {$node->server}<br /><br />"; } Quote Link to comment https://forums.phpfreaks.com/topic/222381-looping-through-foreach-with-xml-data/#findComment-1150285 Share on other sites More sharing options...
isimpledesign Posted December 22, 2010 Author Share Posted December 22, 2010 This is great thanks so much sorted me out. it works prefectly just needed to change. foreach($xml->response->account as $node){ to foreach($xml->account as $node){ Thanks Quote Link to comment https://forums.phpfreaks.com/topic/222381-looping-through-foreach-with-xml-data/#findComment-1150286 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.