0

我有一个对象构造函数,它使用 xmlfile 来设置方法的属性。构造函数通过

$this->xml_file = simplexml_load_file('xml/settings.xml');

这是 xml 文件的样子:

<?xml version="1.0"?>
<settings>
   <contents>
      <content>
         <item>a</item>
         <title>A</title>
         <keywords></keywords>
      </content>
      <content>
         <item>b</item>
         <title>B</title>
         <keywords></keywords>
      </content>
      <content>
         <item>c</item>
         <title>C</title>
         <keywords></keywords>
      </content>
   <errors_escape>
      <error_escape>one</error_escape>
      <error_escape>two</error_escape>
      <error_escape>three</error_escape>
   </errors_escape>
</settings>

我想用这些信息创建两个数组。应该看起来像:

protected $all_settings = array(
         array('item' => 'a', 'title' => 'A', 'keywords' => ''),
         array('item' => 'b', 'title' => 'B', 'keywords' => ''),
         array('item' => 'c', 'title' => 'C', 'keywords' => ''),
      );
protected $errors_escape = array('one', 'two', 'three');

我已经尝试并阅读了有关此主题的不同问题,但除了在它说的地方创建数组之外我什么也做不了

[title] => SimpleXMLElement Object
                (
                    [0] => A
                )

或者

[title] => SimpleXMLElement Object
                (
                )
4

1 回答 1

0

假设您的遗漏</contents>如下:

<?xml version="1.0"?>
<settings>
   <contents>
      <content>
         <item>a</item>
         <title>A</title>
         <keywords></keywords>
      </content>
      <content>
         <item>b</item>
         <title>B</title>
         <keywords></keywords>
      </content>
      <content>
         <item>c</item>
         <title>C</title>
         <keywords></keywords>
      </content>
   </contents> <!-- missing -->
   <errors_escape>
      <error_escape>one</error_escape>
      <error_escape>two</error_escape>
      <error_escape>three</error_escape>
   </errors_escape>
</settings>

你可以这样做:

$this->all_settings=array();
$this->error_escape=array();
foreach($this->xml_file->contents->content as $node)
{
    $this->all_settings[]=array("item"=>strval($node->item),"title"=>strval($node->title),"keywords"=>strval($node->keywords));
}
foreach($this->xml_file->errors_escape->error_escape as $node)
{
    $this->error_escape[]=strval($node);
}
//print_r($this->all_settings);
//print_r($this->error_escape);

在线演示

两个调试print_r输出:

Array
(
    [0] => Array
        (
            [item] => a
            [title] => A
            [keywords] => 
        )

    [1] => Array
        (
            [item] => b
            [title] => B
            [keywords] => 
        )

    [2] => Array
        (
            [item] => c
            [title] => C
            [keywords] => 
        )

)
Array
(
    [0] => one
    [1] => two
    [2] => three
)
于 2013-10-28T10:20:51.983 回答