سؤال

I tried writing into my XML file with simpleXML and I wanted to write a string with the value "<test>asd</test>" then it turned into total giberrish (I know this is related with encoding formats but I don't know the solution to fix this, I tried turning into encoding="UTF-8" but it still yield a similar result)

My XML File:

<?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>&lt;test&gt;asd&lt;/test&gt;</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>

My PHP File:

    <?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();


?>

Thank you and have a nice day =)

هل كانت مفيدة؟

المحلول

This isn't gibberish; it is simply the XML entities for < (&lt;) and > (&gt;). To add nested XML elements with SimpleXML, you can do the following:

$node = $account->addChild('systemInfo');
$node->addChild('test', 'asd');

You'll see that first we add a node to <account>, then add a child to that newly created node.

If you plan on adding several children to the <systemInfo> element, you could perhaps do the following:

$items = array(
    'os' => 'Windows 7',
    'ram' => '8GB',
    'browser' => 'Google Chrome'
);
$node = $account->addChild('systemInfo');
foreach ($items as $key => $value) {
    $node->addChild($key, $value);
}

نصائح أخرى

The addChild function is used to add the child element to an Xml node. You are trying to add xml instead of text.

You have

$meow = "<test>asd</test>";
$account->addChild('systemInfo',$meow);

You should change it to

$account->addChild('systemInfo','my system info text');
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top