How to use foreach with PHP & XML (simplexml)

后端 未结 7 819
谎友^
谎友^ 2020-12-10 06:47

Anyone that knows PHP and XML out there? Then please have a look!

This is my PHP code:



        
相关标签:
7条回答
  • 2020-12-10 07:16
    <? foreach($movie->regions->region->categories->categorie as $category) { ?>
    <p>Categori: <?= $category ?></p>
    <? } ?>
    
    0 讨论(0)
  • 2020-12-10 07:21
    function categoryList(SimpleXmlElement $categories){
      $cats = array();
      foreach($categories as $category){
        $cats[] = (string) $category;
      }
    
      return implode(', ', $cats);
    
    }
    

    Then you can jsut call it from your loop like:

    <? echo categoryList($movie->regions->region->categories); ?>
    

    Using an array and implode removes the need for logic of counting and detecting the last category.

    Isolating it in a function makes it easier to maintain and is less confusing than nesting the loop (though admittedly nested loops arent that confusing).

    0 讨论(0)
  • 2020-12-10 07:25

    this is how you use foreach with an simplexmlElement:

    $xml = simplexml_load_file("movies.xml");
    foreach ($xml->children() as $children) {
        echo $children->name;
    }
    
    0 讨论(0)
  • 2020-12-10 07:33

    Try this.

    <?php
    $xml = simplexml_load_file("movies.xml");
    foreach ($xml->movie as $movie) {
    
        echo '<h2>' . $movie->title . '</h2>';
        echo '<p>' . $movie->year . '</p>';
    
        $categories = $movie->regions->region->categories->categorie;
    
        while ($categorie = current($categories)) {
            echo $categorie;
            echo next($categories) ? ', ' : null;
        }
    
        echo '<p>' . $movie->countries->country . '</p>';
    }
    ?>
    
    0 讨论(0)
  • 2020-12-10 07:34
    <?php
    $cat_out='';
    foreach($movie->regions->region->categories->categorie as $cat){
     $cat_out.= $cat.',';
    }
    echo rtrim($cat_out,',');
    ?>
    
    0 讨论(0)
  • 2020-12-10 07:37

    You need to iterate through the categorie elements too, in the same way you've iterated through movies.

    echo '<p>';
    foreach($movie->regions->region->categories->categorie as $categorie){
        echo $categorie . ', ';
    }
    echo '</p>';
    

    You'll probably want to trim the trailing , as well.


    The method mentioned in my comment:

    $categories = $movie->regions->region->categories->categorie;
    while($category = current($categories)){
        echo $category . next($categories) ? ', ' : '';
    }
    
    0 讨论(0)
提交回复
热议问题