简体   繁体   中英

PHP - how to display all children of a parents array

Hi I am able to parse the array, however I am having trouble parse all sub item (children), it only shows first item of the children.

$xml_data = 
'<response>
<item>
  <name>Life Cover1</name>
  <feature>Indexation1</feature>
  <benefits>
    <bitem>foo1</bitem>
    <bitem>foo2</bitem>
  </benefits>
</item>
<item>
  <name>Life Cover2</name>
  <feature>Indexation2</feature>
  <benefits>
    <bitem>fd1</bitem>
    <bitem>foo3</bitem>
    <bitem>foo4</bitem>
  </benefits>
</item>
<item>
  <name>Life Cover3</name>
  <feature>Indexation3</feature>
  <benefits>
    <bitem>foo5</bitem>
    <bitem>foo6</bitem>
  </benefits>
</item>
</response>
';

//Display Data output format View
$xml = new SimpleXMLElement($xml_data);

$items = $xml->xpath('//item');
$itemNames = $xml->xpath('//name');
$features = $xml->xpath('//feature');
$benefits = $xml->xpath('//benefits');

$DataSize = sizeof($items);

echo '<table border="1" cellpadding="0" cellspacing="0"><tbody>';

foreach($items as $item){

  echo '<tr>';
  echo '<td>' . $item->name . '</td>';
  echo '<td>' . $item->feature . '</td>';
  echo '<td>' . $item->benefits->children() . '</td>';
  echo '</tr>';
}
echo '</tbody></table>';

The $item->benefits->children(); only show first bitem, how can display all bitem in this kind of parse output?

Thanks

You can try this :

$xml_data = 
'<response>
<item>
  <name>Life Cover1</name>
  <feature>Indexation1</feature>
  <benefits>
    <bitem>foo1</bitem>
    <bitem>foo2</bitem>
  </benefits>
</item>
<item>
  <name>Life Cover2</name>
  <feature>Indexation2</feature>
  <benefits>
    <bitem>fd1</bitem>
    <bitem>foo3</bitem>
    <bitem>foo4</bitem>
  </benefits>
</item>
<item>
  <name>Life Cover3</name>
  <feature>Indexation3</feature>
  <benefits>
    <bitem>foo5</bitem>
    <bitem>foo6</bitem>
  </benefits>
</item>
</response>
';

//Display Data output format View
$xml = new SimpleXMLElement($xml_data);

$items = $xml->xpath('//item');
$itemNames = $xml->xpath('//name');
$features = $xml->xpath('//feature');
$benefits = $xml->xpath('//benefits');

$DataSize = sizeof($items);

echo '<table border="1" cellpadding="0" cellspacing="0"><tbody>';

foreach($items as $item){

  echo '<tr>';
  echo '<td>' . $item->name . '</td>';
  echo '<td>' . $item->feature . '</td>';
  echo '<td>';
  $child_item = '';
  foreach($item->benefits->children() as $child)
  {
    $child_item .= $child.' ,';
  }
  echo rtrim($child_item,' ,');
  echo  '</td>';
  echo '</tr>';
}
echo '</tbody></table>';

This will display all the child item with comma seperated string. Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM