php 使用 foreach() 解析 XML 子项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2706912/
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 07:25:32  来源:igfitidea点击:

Parse XML subitems using foreach()

phpxmlforeach

提问by user

I have an XML file that needs parsing in PHP. I am currenlty using simplexml_load_file to load the file like so:

我有一个需要在 PHP 中解析的 XML 文件。我目前使用 simplexml_load_file 加载文件,如下所示:

$xml = simplexml_load_file('Project.xml');

Inside that XML file lies a structure like this:

在那个 XML 文件中有一个这样的结构:

<?xml version="1.0" encoding="ISO-8859-1"?>
<project>
<name>Project 1</name>
<features>
    <feature>Feature 1</feature>
    <feature>Feature 2</feature>
    <feature>Feature 3</feature>
    <feature>Feature 4</feature>
</features>
</project>

What I am trying to do is print the <name>contents along with EACH <feature>element within <features>. I'm not sure how to do this because there is more than 1 element called <feature>. Any help is greatly appreciated.

我所试图做的是打印的<name>内容与各自沿着<feature>内元素<features>。我不知道如何做到这一点,因为有超过 1 个元素被称为<feature>. 任何帮助是极大的赞赏。

回答by Puaka

to print the text, try this :

要打印文本,请尝试以下操作:

foreach($xml->features->feature as $key => $value)
{
    echo $value;
}

回答by timdev

simplexml_load_file() returns an object.

simplexml_load_file() 返回一个对象。

Have a look at the structure with var_dump($xml):

看一下 var_dump($xml) 的结构:

object(SimpleXMLElement)#1 (2) {
  ["name"]=>
  string(9) "Project 1"
  ["features"]=>
  object(SimpleXMLElement)#2 (1) {
    ["feature"]=>
    array(4) {
      [0]=>
      string(9) "Feature 1"
      [1]=>
      string(9) "Feature 2"
      [2]=>
      string(9) "Feature 3"
      [3]=>
      string(9) "Feature 4"
    }
  }
}

So code like this:

所以代码如下:

<?PHP
$xml = simplexml_load_file('test.xml');
echo $xml->name . "\n";
foreach($xml->features->feature as $f){
  echo "\t$f\n";
}

Will produce output like:

将产生如下输出:

Project 1
    Feature 1
    Feature 2
    Feature 3
    Feature 4

Which is what I assume you're after, more or less.

这就是我假设你或多或少所追求的。

回答by codaddict

You can do:

你可以做:

foreach($xml->features->feature as $f) {
    echo $f."\n";
}