我尝试使用simpleXML写入我的XML文件,我想写一个值为"<test>asd</test>"
的字符串然后变成完全giberrish(我知道这与编码格式有关,但我不知道解决方案要解决这个问题,我尝试转入encoding="UTF-8"
,但仍会产生类似的结果)
我的XML文件:
<?xml version="1.0"?>
<userinfos>
<userinfo>
<account>
<user>TIGERBOY-PC</user>
<toDump>2014-02-04 22:17:22</toDump>
<nextToDump>2014-02-05 00:17:22</nextToDump>
<lastChecked>2014-02-04 16:17:22</lastChecked>
<isActive>0</isActive>
<upTime>2014-02-04 16:17:22</upTime>
<toDumpDone>1</toDumpDone>
<systemInfo><test>asd</test></systemInfo>
</account>
<account>
<user>TIGERBOY-PCV</user>
<toDump>2014-02-04 22:17:22</toDump>
<nextToDump>2014-02-05 00:17:22</nextToDump>
<lastChecked>2014-02-04 16:17:22</lastChecked>
<isActive>1</isActive>
<upTime>2014-02-04 16:17:22</upTime>
<toDumpDone>1</toDumpDone>
</account>
</userinfo>
</userinfos>
我的PHP文件:
<?php
//Start of Functions
function changeAgentInfo()
{
$userorig = $_POST['user'];
$userinfos = simplexml_load_file('userInfo.xml'); // Opens the user XML file
$flag = false;
foreach ($userinfos->userinfo->account as $account)
{
// Checks if the user in this iteration of the loop is the same as $userorig (the user i want to find)
if($account->user == $userorig)
{
$flag = true; // Flag that user is found
$meow = "<test>asd</test>";
$account->addChild('systemInfo',$meow);
}
}
$userinfos->saveXML('userInfo.xml');
echo "Success";
}
//End of Functions
// Start of Program
changeAgentInfo();
?>
谢谢你,祝你有个美好的一天=)
答案 0 :(得分:2)
这不是胡言乱语;它只是<
(<
)和>
(>
)的XML entities。要使用SimpleXML添加嵌套的XML元素,您可以执行以下操作:
$node = $account->addChild('systemInfo');
$node->addChild('test', 'asd');
您首先会看到add a node到<account>
,然后将子项添加到新创建的节点。
如果您打算在<systemInfo>
元素中添加多个子元素,则可以执行以下操作:
$items = array(
'os' => 'Windows 7',
'ram' => '8GB',
'browser' => 'Google Chrome'
);
$node = $account->addChild('systemInfo');
foreach ($items as $key => $value) {
$node->addChild($key, $value);
}
答案 1 :(得分:0)
addChild function用于将子元素添加到Xml节点。您正在尝试添加xml而不是文本。
你有
$meow = "<test>asd</test>";
$account->addChild('systemInfo',$meow);
您应该将其更改为
$account->addChild('systemInfo','my system info text');