Jump to content

Looping through foreach with xml data


isimpledesign

Recommended Posts

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

 

Link to comment
https://forums.phpfreaks.com/topic/222381-looping-through-foreach-with-xml-data/
Share on other sites

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.