0

I have an object constructor which uses an xmlfile to set the properties of the method. The constructor accesses it by

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

This is how the xml file looks like:

<?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>

I'd like to create two arrays with this information. The should look like:

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');

I've tried and read different questions on this topic, but I can't do anything but create arrays where it says

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

or

[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);

オンラインデモ

2 つのデバッグ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 に答える