如何在 PHP 和 XML 中使用 foreach (simplexml)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4637617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:47:23  来源:igfitidea点击:

How to use foreach with PHP & XML (simplexml)

phpxmlsimplexml

提问by Hakan

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

有人知道 PHP 和 XML 吗?那么请看一看!

This is my PHP code:

这是我的 PHP 代码:

<? $xml = simplexml_load_file("movies.xml");
foreach ($xml->movie as $movie){ ?>

<h2><? echo $movie->title ?></h2>
<p>Year: <? echo $movie->year ?></p>
<p>Categori: <? echo $movie->regions->region->categories->categorie ?></p>
<p>Country: <? echo $movie->countries->country ?></p>

<? } ?>

This is mys XML file:

这是我的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<movies>
 <movie>
  <title>A movie name</title>
  <year>2010</year>
     <regions>
   <region>
    <categories>
      <categorie id="3">Animation</categorie>
      <categorie id="5">Comedy</categorie>
      <categorie id="9">Family</categorie>
     </categories>
    <countries>
     <country id="123">USA</country>
    </countries>
   </region>
  </regions>
 </movie>
 <movie>
  <title>Little Fockers</title>
  <year>2010</year>
     <regions>
   <region>
    <categories>
     <categorie id="5">Comedy</categorie>
             </categories>
        <countries>
         <country id="123">USA</country>
    </countries>
   </region>
  </regions>
 </movie>
</movies>

The outcome of the code above is:

上面代码的结果是:

<h2>A movie name</h2>
<p>Year: 2010</p>
<p>Category: Animation</p>
<p>Country: USA</p>

<h2>Little Fockers</h2>
<p>Year: 2010</p>
<p>Category: Comedy</p>
<p>Country: USA</p>

I want it to be like this (see category on the first movie):

我希望它是这样的(见第一部电影的类别):

<h2>A movie name</h2>
<p>Year: 2010</p>
<p>Category: Animation, Comedy, Family</p>
<p>Country: USA</p>

<h2>Little Fockers</h2>
<p>Year: 2010</p>
<p>Category: Comedy</p>
<p>Country: USA</p>

Note: Also I wonder how to get the comma between the words, but without a comma on the last word...

注意:我还想知道如何在单词之间使用逗号,但最后一个单词上没有逗号...

回答by Jonah

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>';
}
?>

回答by Sebastian Viereck

this is how you use foreach with an simplexmlElement:

这是将 foreach 与 simplexmlElement 一起使用的方式:

$xml = simplexml_load_file("movies.xml");
foreach ($xml->children() as $children) {
    echo $children->name;
}

回答by Sebastian Viereck

<?php
$cat_out='';
foreach($movie->regions->region->categories->categorie as $cat){
 $cat_out.= $cat.',';
}
echo rtrim($cat_out,',');
?>

回答by Dan Lugg

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

您也需要遍历categorie元素,就像遍历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) ? ', ' : '';
}

回答by dqhendricks

<? foreach($movie->regions->region->categories->categorie as $category) { ?>
<p>Categori: <?= $category ?></p>
<? } ?>

回答by prodigitalson

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 imploderemoves the need for logic of counting and detecting the last category.

使用数组并implode消除对计数和检测最后一个类别的逻辑的需要。

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

将它隔离在一个函数中使它更容易维护并且比嵌套循环更容易混淆(尽管诚然嵌套循环并不那么令人困惑)。

回答by Ajay Kumar

Try This one

试试这个

$xml = ... // Xml file data
$Json = Xml_to_Json($xml);
$array = json_decode($Json,true);
echo '<pre>'; print_r($array);
foreach ($array as $key => $value) {
    foreach ($value as $key1 => $value1) {
        echo '<h2>'.$value1['title'].'</h2>
        <p>Year: '.$value1['year'].'</p>
        <p>Category: ';
        foreach ($value1['regions']['region']['categories']['categorie'] as $categoriekey => $categorie) {
            echo $categorie.' ';                
        }
        echo 'Animation</p>
        <p>Country: '.$value1['regions']['region']['countries']['country'].'</p>';
    }
}

function Xml_to_Json($array){
    $xml = simplexml_load_string($array, "SimpleXMLElement", LIBXML_NOCDATA);
    $json = json_encode($xml);
    return $json;
}