0

This is an example xml which i need to access its elements. In this example, I need to perform a loop to add another -> to move to another element. I will get values from XML not generate an XML

<Person>
      <Address>
         <State>
            <Code>101</Code>
         </State>
      </Address>    
</Person>    
<Person>
      <Address>
         <State>
            <Code>101</Code>
         </State>
         <Phone> 123456789</Phone>
      </Address>   
</Person>

Code:

for($i=0; $i< count(Person); $i++)
{
  $element .= '->{<<element>>['.$i.']}';            
}

//output would something be like an element to get data from XML:        `
$person->{'Address'}->{'State'}->{'Code'};`
dairinjan
  • 63
  • 1
  • 7
  • Possible duplicate of [How to generate XML file dynamically using PHP?](https://stackoverflow.com/questions/486757/how-to-generate-xml-file-dynamically-using-php) – Loek Jul 04 '18 at 14:42
  • hi, im not trying to generate an XML, i am accessing its element dynamically – dairinjan Jul 04 '18 at 14:46

1 Answers1

0

I think you might want to use SimpleXML.

The $item in the loop is of type SimpleXMLElement from which you can get the properies like $item->Address->State->Code

$data = <<<DATA
<Persons>
<Person>
      <Address>
         <State>
            <Code>101</Code>
         </State>
      </Address>    
</Person>    
<Person>
      <Address>
         <State>
            <Code>101</Code>
         </State>
         <Phone> 123456789</Phone>
      </Address>   
</Person>
</Persons>
DATA;

$items = simplexml_load_string($data);
foreach ($items as $item) {
    echo $item->Address->State->Code;
}

Demo

If you want to use a for loop and a counter, you might use:

$items = simplexml_load_string($data);
$count = count($items->Person);
for ($i = 0; $i < $count; $i++) {
    echo $items->Person[$i]->Address->State->Code;
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • For this one: `foreach ($items as $item) { echo $item->Address->State->Code; }` is there a way like to mke it something like `$total_elements_inside_item= count($items); for($i=0;$i<=$total_elements_inside_item $i++) { $item->{element[0]} then next loop wil be $item->{element[1]}->{element[2]} }` – dairinjan Jul 04 '18 at 15:36
  • @djan I have added an update to my answer. But why not use the `foreach`? – The fourth bird Jul 04 '18 at 15:55