解析xml文件将无法正常工作

时间:2013-10-28 10:01:16

标签: xml xml-parsing simplexml

我有一个对象构造函数,它使用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
                (
                )

1 个答案:

答案 0 :(得分: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);

Online demo

两个调试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
)
相关问题