代码之家  ›  专栏  ›  技术社区  ›  Jason

PHP SimpleXML-多个子级同名

  •  4
  • Jason  · 技术社区  · 8 年前

    我目前正在用以下php代码生成一个xml文件。它接受表单输入并将其放入xml文件中。

    我想有多个同名的孩子。如:

    <person>
      <address>
        <street>streetname</street>
        <streetnumber>streetnumber</streetnumber>
      </address>
      <address>
        <street>streetname</street>
        <streetnumber>streetnumber</streetnumber>
      </address>
    </person>  
    

    我生成xml的代码遵循这种结构;

    //Add first address - working
    
    $xml->person = "";
    $xml->person->address = "";
    
    $xml->person->address->addChild('streetname', $_POST['streetname1']);
    $xml->person->address->addChild('streetnumber', $_POST['streetnumber1']);
    
    
    //Attempt to add second address, doesn't work
    
    $xml->person->address = "";
    
    $xml->person->address->addChild('streetname', $_POST['streetname2']);
    $xml->person->address->addChild('streetnumber', $_POST['streetnumber2']);
    
    1 回复  |  直到 8 年前
        1
  •  4
  •   Patrick Lee    8 年前

    在构建XML文档时,使用变量要简单得多,也不那么冗长。然后您可以添加多个 <address> 元素添加到您的 <person> 这样的元素。。。

    $person = $xml->addChild('person');
    
    $address1 = $person->addChild('address');
    $address1->addChild('streetname', $_POST['streetname1']);
    $address1->addChild('streetnumber', $_POST['streetnumber1']);
    
    $address2 = $person->addChild('address');
    $address2->addChild('streetname', $_POST['streetname2']);
    $address2->addChild('streetnumber', $_POST['streetnumber2']);