在空子项后添加XML子项

时间:2017-07-05 13:40:10

标签: php simplexml

我想从对象页面创建一个XML文档,其中包含有关打印页面的一些信息。我正在使用此代码:

$xml = new \SimpleXMLElement('<page/>');
$xml->addChild( "pageid", $page->id );
$xml->addChild( "keyword", $page->page_name );

$elements = $xml->addChild( "elements" );

foreach ( $page->elements as $page_element ) {
    $element = $elements->addChild( "element" );
    $element->addChild( "type", $page_element["type"] );
    $element->addChild( "id", $page_element["id"] );
    $element->addChild( "parentContainerID", $page_element["parent_container_id"] );
    $element->addChild( "parentContainerType", $page_element["parent_container_type"] );
    $element->addChild( "Width", $page_element["width"] ?? 0 );
    $element->addChild( "Height", $page_element["height"] ?? 0 );
    $user_def_fields = $element->addChild( "UserDefFields" );

    if ( isset( $page_element["custom_fields"] ) ) {
            foreach ( $page["custom_fields"] as $custom_field_name => $custom_field_value ) {
                $user_def_field = $user_def_fields->addChild( "field" );
                $user_def_field->addChild( "label", $custom_field_name );
                $user_def_field->addChild( "value", $custom_field_value );
            }                        
        }
    }

    $states = $element->addChild( "ArticleStates" );

    foreach( $page_element["article_states"] as $state ) {
        $states->addChild( "articlestate", $state );
    }
}

这有效 - 但是当article_states为空时,我得到了这个:

<element>
  <type>group</type>
  <id>1234</id>
  <parentcontainerid>2345</parentcontainerid>
  <parentcontainertype>article</parentcontainertype>
  <width>0</width>
  <height>0</height>
  <userdeffields>
    <articlestates></articlestates>
  </userdeffields>
</element>

articlesstates标签位于userdeffields内。那是错的,它应该是这样的:

<element>
  <type>group</type>
  <id>1234</id>
  <parentcontainerid>2345</parentcontainerid>
  <parentcontainertype>article</parentcontainertype>
  <width>0</width>
  <height>0</height>
  <userdeffields></userdeffields>
  <articlestates></articlestates>      
</element>

ħ

1 个答案:

答案 0 :(得分:0)

非常简单......但确实很奇怪。 只需添加如下空格:

$user_def_fields = $element->addChild( "UserDefFields", " " );

我只需要记住在解析XML时使用trim函数... JSON ftw: - )