【问题标题】:PHP - Inserting into and getting from XML filePHP - 插入和获取 XML 文件
【发布时间】:2015-04-29 21:34:44
【问题描述】:

我使用 JSON 为聊天系统编写了以下代码:

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");

这将获取事务文件的内容,对其进行解码,插入从 $_GET 获取的名称和消息,将其推送到数组中并将其编码回字符串并放入事务文件中。

这很好用,但是我需要为 XML 而不是 JSON 做完全相同的事情。所以文件中的字符串看起来像这样:

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

这就是 JSON 现在的样子:

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

另外,还有一件事,我该如何命名那个 JSON 对象?所以它看起来像这样:

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

最后一部分可能比我想象的要容易,但我没有运气。

我真的希望你能帮助我。谢谢。

【问题讨论】:

  • 不错。事情是这样的;这是一个项目,我必须从一开始就将其编写为 XML,而不是 JSON,然后转换为 XML。
  • 您可以在不使用 JSON 的情况下将 PHP 数组转换为 XML。

标签: php arrays xml json get


【解决方案1】:

如果您想将“消息”放在该名称的元素下,您只需要确保您的数组遵循该格式。你也没有定义$arrne,你需要先将它设置为一个array(),你可以简写如下。

$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 );

【讨论】:

  • 感谢您的帮助。但这并不完全正确。多次运行您编写的代码将使其看起来像这样(3 次) { "messages": { "messages": { "messages": [ { "name": "name", "message": "S" } ], "0": { "name": "name", "message": "S" } }, "0": { "name": "name", "message": "S" } } }
  • 这段代码只是一个例子,它没有被设置为支持循环多条消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多