我正在尝试使用PHP和SimpleXML在XML文件中编辑客户的值。我似乎能够将新数据写入文件,并编辑客户的值,但我无法将这些更改保存到文件中。
我试过chmod 777 -R,这个项目位于我的服务器上,但没有任何变化,我也可以用另一种方法将新数据写入同一个customers.xml文件,所以我排除了一个问题权限。另外,我尝试使用file_put_contents()保存文件但效果不佳。
此函数的目标是执行XPath表达式以获取要修改的客户,更新该客户的值,然后将该客户的已编辑更改保存到文件,以及XML的其余部分文档 - 应该保持不变,因为一次只能更新一个客户。
$customersXml = simplexml_load_file('customers.xml', null, true) or die('Error: Cannot load XML from file customers.xml"');
$customerToEdit = $customersXml->xpath('//customer[position()="'.$customerIndexOfMatch.'"]/customerInfo');
if (isset($_POST['updateCustomer'])){
// updating the data seems to work fine
$customerToEdit[0]->firstName = $_POST['edit-fname'];
$customerToEdit[0]->middleName = $_POST['edit-mname'];
$customerToEdit[0]->lastName = $_POST['edit-lname'];
$customerToEdit[0]->address = $_POST['edit-address'];
$customerToEdit[0]->telephone[0] = $_POST['edit-ph1'];
$customerToEdit[0]->telephone[1] = $_POST['edit-ph2'];
$customerToEdit[0]->telephone[2] = $_POST['edit-ph3'];
// but when it comes to saving the updated data, i'm baffled (this method of saving has worked in another function)
// have also tried file_put_contents('customers.xml', $customersXml->asXML()) which doesn't work here
$customersXml->asXML('customers.xml');
echo '<pre>';
var_dump($customerToEdit);
}
将客户Bart的名称更改为荷马后,var_dump()的输出:
array(1) {
[0]=>
object(stdClass)#3 (5) {
["firstName"]=>
string(4) "Homer"
["middleName"]=>
string(0) ""
["lastName"]=>
string(7) "Simpson"
["address"]=>
string(28) " ... "
["telephone"]=>
array(3) {
[0]=>
string(10) "111222333"
[1]=>
string(10) "444555666"
[2]=>
string(10) "777888999"
}
}
}
此外,这是我的XML文档的结构:
<customers>
<customer number="" meterNumber="">
<customerInfo>
<title></title>
<firstName></firstName>
<middleName></middleName>
<lastName></lastName>
<address></address>
<telephone></telephone>
<telephone></telephone>
<telephone></telephone>
</customerInfo>
<prevMeterReadings>
<reading />
<prevMeterReadings>
</customer>
</customers>
任何帮助将不胜感激!希望编辑的数据能够正确保存到文件中!
答案 0 :(得分:0)
好的,我已经弄清了问题所在。
解决方案是改变以下行:
$customerToEdit[0]->firstName = $_POST['edit-fname'];
...
到
$customersXml->customer[$customerIndexOfMatch]->customerInfo->firstName = $_POST['edit-fname'];
...