Php 从XML开始

Php 从XML开始,php,xml,domdocument,Php,Xml,Domdocument,刚开始使用XML,有点麻烦。我已经创建了一个XML文档。这个xml文档被用作我的网站注册用户的数据库 customer.xml <?xml version="1.0"?> <customers> <customer> <firstname>John</firstname> <lastname>Willson</lastname> <email>a@b.c</email&g

刚开始使用XML,有点麻烦。我已经创建了一个XML文档。这个xml文档被用作我的网站注册用户的数据库

customer.xml

<?xml version="1.0"?>
<customers>
<customer>
    <firstname>John</firstname>
    <lastname>Willson</lastname>
    <email>a@b.c</email>
    <custid>1111</custid>
    <password>Pa$$w0rd</password>
</customer>
我接着使用print$dom->saveXML;但不幸的是,它表明xml文档中没有任何变化。它只显示原始文档中显示的信息。我对XML非常陌生,所以任何关于我做错了什么的解释都会很好


干杯,

您忘记将新节点customer节点附加到futur父节点customers,并且您已经为customer编写了一个大写C。您正在将新节点的节点内容设置为属性,但这些是节点值或子节点、文本节点,而不是属性

$xmlFile = "customer.xml";
$dom = DOMDocument::load($xmlFile);

$customer = $dom->createElement( "customer" ); // here
$firstname = $dom->createElement( "firstname" );
$lastname = $dom->createElement( "lastname" );
$email = $dom->createElement( "email" );
$password = $dom->createElement( "password" );
$custid = $dom->createElement( "custid" );

$firstname->nodeValue = 'Fred';
$lastname->nodeValue = 'Fredson';
$email->nodeValue = 'd@e.f';
$password->nodeValue = 'Pa$$w0rd2'; // be careful with $ and double quotes
$custid->nodeValue = '2222';

$customer->appendChild($firstname);
$customer->appendChild($lastname);
$customer->appendChild($email);
$customer->appendChild($password);
$customer->appendChild($custid);

$dom->getElementsByTagName('customers')->item(0)->appendChild($customer);
简单XML就是你的答案。


首先,您显然没有看到PHP通知,也可能没有看到警告和错误,因为您的代码触发了其中一些警告和错误:

// Strict standards: Non-static method DOMDocument::load() should not be called statically
$dom = DOMDocument::load($xmlFile);
你想要:

$dom = new DOMDocument();
$dom->load($xmlFile);
$password->setAttribute( "password", 'Pa$$w0rd2' ); // Single quotes
$customer = $dom->createElement( "customer" );
$dom->getElementsByTagName('customers')->item(0)->appendChild($customer);
//注意:未定义变量:w0rd2 $password->setAttribute密码,Pa$$w0rd2; 你想要:

$dom = new DOMDocument();
$dom->load($xmlFile);
$password->setAttribute( "password", 'Pa$$w0rd2' ); // Single quotes
$customer = $dom->createElement( "customer" );
$dom->getElementsByTagName('customers')->item(0)->appendChild($customer);
在继续之前,您需要配置完整的错误报告

修复了这个问题,还有一些其他问题。XML区分大小写:

$customer = $dom->createElement( "Customer" );
你想要:

$dom = new DOMDocument();
$dom->load($xmlFile);
$password->setAttribute( "password", 'Pa$$w0rd2' ); // Single quotes
$customer = $dom->createElement( "customer" );
$dom->getElementsByTagName('customers')->item(0)->appendChild($customer);
创建此节点并将其他所有内容附加到该节点,但从未将其插入文档中。你想要:

$dom->getElementsByTagName('customers')->item(0)->appendChild($customer);

此外,正如在另一个答案中指出的,示例XML不使用属性。您需要为数据创建其他节点。我将把它作为练习留给读者-

提醒:SimpleXML将被格式不正确的XML扼杀。正确,但如果程序员不能让其他东西工作,则更简单。最好使用真实的数据库。在结尾处缺少XML。XML由节点组成,元素是最明显的,但只有一种类型。您有单独的方法来创建节点createElement、createTextNode等。。。我希望这只是一个自学XML和DOM的个人项目。普通文件很难获得正确的并发访问权限,更不用说XML的扩展有多糟糕了。不要直接设置nodeValue。实体处理有一个问题: