【问题标题】:Saving XML In Correct Format Using PHP And DOM使用 PHP 和 DOM 以正确的格式保存 XML
【发布时间】:2012-10-30 17:28:33
【问题描述】:

我在使用 PHP 和 DOM 更新我的 XML 时遇到问题。我的 XML 文件是这种格式:

原始 XML(和所需的 xml 布局):

<?xml version="1.0" standalone="yes"?>
<Rows>
  <Row CustomerAccountNumber="COU002" />
  <Row CustomerAccountNumber="COU023" />
  <Row CustomerAccountNumber="C2335" />
  <Row CustomerAccountNumber="CvbU002" />

保存的代码,即将新记录添加到 XML(customer.xml) 是:

<?php

$xmldoc=new DOMDocument();
$xmldoc->load('XML/customer.xml');

$newAct= 'c12345';

$root = $xmldoc->firstChild;

$newElement= $xmldoc->createElement('CustomerAccountNumber');
$root->appendChild($newElement);
$newText= $xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);

$xmldoc->save('XML/customer.xml');
 ?>

问题:代码正在以这种格式生成新记录:

  <Rows>
  <Row CustomerAccountNumber="COU002" />
  <Row CustomerAccountNumber="COU023" />
  <Row CustomerAccountNumber="C2335" />
  <Row CustomerAccountNumber="CvbU002" />
  <CustomerAccountNumber>c12345</CustomerAccountNumber>

</Rows>

我不明白我在哪里犯了错误。我只想保留我原来的 XML 格式。我想要上面提到的原始格式的输出文件(见顶部)。请指导我并指出我犯错的地方那是在文件本身中生成不正确的格式。请帮助

【问题讨论】:

    标签: php xml dom xml-parsing


    【解决方案1】:

    您的问题是您当前正在创建一个新的CustomerAccountNumber 元素。相反,您想创建一个新的Row 元素,然后是create a new CustomerAccountNumber attribute

    $newElement = $xmldoc->createElement('Row');
    $newAttribute = $xmldoc->createAttribute('CustomerAccountNumber');
    $newAttribute->value = $newAct;
    $newElement->appendChild($newAttribute);
    $root->appendChild($newElement);
    

    【讨论】:

      猜你喜欢
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 2013-12-04
      相关资源
      最近更新 更多