PHP - 插入XML文件并从中获取

I've written the following, using JSON, for a chat system:

header('Content-type: application/json');

$theName = $_GET['name'];
$theMessage = $_GET['message'];

$str = file_get_contents("transactions.json");

if ($str == ""){
     $str = '[]';
}

$arr = json_decode($str, true);

$arrne['name'] = "$theName";
$arrne['message'] = "$theMessage";

array_push($arr, $arrne);   

$aFinalTransaction = json_encode($arr, JSON_PRETTY_PRINT);
echo $aFinalTransaction;

file_put_contents("transactions.json", "$aFinalTransaction");

This gets the content of the transactions file, decodes it, insert the name and messages taken from $_GET, pushes it into the array and encodes it back into a string and puts it into the transactions file.

This works fine, however I need to do the exact same thing just for XML instead of JSON. So the string from the file would look something like this:

<chatMessage>
 <name>Name1</name>
 <message>Msg1</message>
</chatMessage>
<chatMessage>
 <name>Name2</name>
 <message>Msg2</message>
</chatMessage>

This is how is looks right now in JSON:

[
    {
        "name": "Name1",
        "message": "Msg1"
    },
    {
        "name": "Name2",
        "message": "Msg2"
    }
]

Also, one more thing, how exactly would I name that JSON object? So it'd look something like this instead:

{"messages":[
    {
        "name": "Name1",
        "message": "Msg1"
    },
    {
        "name": "Name2",
        "message": "Msg2"
    }
]}

This last part is probably easier than I think, but I haven't had any luck.

I really hope you can help me. Thanks.

If you want to have your "messages" under an element of that name, you just need to make sure your array follows that format. You are also not defining $arrne, you need to set it to an array() first, which you can shorthand as seen below.

$str = file_get_contents( "transactions.json" );

// check if $str is a blank string, false, null, etc
if ( empty( $str ) ){
    // it's empty so create an array
    $arr = array();
} else {
    // it's not empty so decode the JSON string
    $arr = json_decode( $str, true );
}

// use isset() to avoid undefined index warnings
array_push( $arr, array(
    'name' => isset( $_GET['name'] )? $_GET['name'] : "",
    'message' => isset( $_GET['message'] )? $_GET['message'] : "",
) ); 

// assign to a new array with all the messages under the key "messages"
$result = array( 'messages' => $arr );

// convert array to JSON. see comment above for converting to XML with SimpleXML
$json = json_encode( $result, JSON_PRETTY_PRINT );