【发布时间】:2017-07-04 19:46:54
【问题描述】:
我需要先从服务中读取一些纯 XML 代码(已排序),它看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<bookcase>
<book>
<id>1</id>
<title>Murder1</title>
<author>John doe</author>
<heading>Reminder to read</heading>
<body>A very exciting book etc</body>
</book>
<book>
<id>2</id>
<title>Murder2</title>
<author>Jane doe</author>
<heading>Reminder to read to</heading>
<body>Also a very exciting book</body>
</book>
</bookcase>
然后我有这段代码可以用 JSON 读取它:
$xmlfile = file_get_contents($path);
$ob= simplexml_load_string($xmlfile);
$json = json_encode($ob);
$configData = json_decode($json, true);
var_dump($configData); 的输出给出:
array(1) { ["book"]=> array(2) {
[0]=> array(5) {
["id"]=> string(1) "1"
["title"]=> string(7) "Murder1"
["author"]=> string(8) "John doe"
["heading"]=> string(16) "Reminder to read"
["body"]=> string(24) "A very exciting book etc" }
[1]=> array(5) {
["id"]=> string(1) "2"
["title"]=> string(7) "Murder2"
["author"]=> string(8) "Jane doe"
["heading"]=> string(19) "Reminder to read to"
["body"]=> string(25) "Also a very exciting book" }
}
}
我在另一个线程中发现了一个我认为可以使用但似乎无法解析多维数组的函数?
function write_ini_file($assoc_arr, $path, $has_sections=FALSE) {
$content = "";
if ($has_sections) {
foreach ($assoc_arr as $key=>$elem) {
$content .= "[".$key."]\n";
foreach ($elem as $key2=>$elem2) {
if(is_array($elem2))
{
for($i=0;$i<count($elem2);$i++)
{
$content .= $key2."[] = \"".$elem2[$i]."\"\n";
}
}
else if($elem2=="") $content .= $key2." = \n";
else $content .= $key2." = \"".$elem2."\"\n";
}
}
}
else {
foreach ($assoc_arr as $key=>$elem) {
if(is_array($elem))
{
for($i=0;$i<count($elem);$i++)
{
$content .= $key."[] = \"".$elem[$i]."\"\n";
}
}
else if($elem=="") $content .= $key." = \n";
else $content .= $key." = \"".$elem."\"\n";
}
}
if (!$handle = fopen($path, 'w')) {
return false;
}
$success = fwrite($handle, $content);
fclose($handle);
return $success; }
write_ini_file($configData, './data.ini', true);
谁能帮助弄清楚如何管理该函数,以便我可以将数组数据保存在 ini 文件中?
更新:只是想分享我发现为我的目的工作的代码。
<?php
$path = ".\data.xml";
$xmlfile = file_get_contents($path);
$ob= simplexml_load_string($xmlfile);
$json = json_encode($ob);
$configData = json_decode($json, true);
foreach($configData as $section => $array) {
foreach($array as $key => $values) {
$ini[] = "\r\n"."[$section-$key]";
foreach($values as $var => $val) {
$ini[] = "$var = \"$val\"";
}
}
}
$ini = implode("\r\n", $ini);
nl2br($ini);
file_put_contents('./data.ini', $ini);
?>
在我的 INI 文件中提供这样的格式:
[book-0]
id = "1"
title = "Murder1"
author = "John doe"
heading = "Reminder to read"
body = "A very exciting book etc"
[book-1]
id = "2"
title = "Murder2"
author = "Jane doe"
heading = "Reminder to read to"
body = "Also a very exciting book"
感谢AbraCadaver
【问题讨论】:
-
为什么是ini文件而不是JSON?如果必须是ini文件,它应该是什么样的?
-
嗨,我要服务的应用程序无法处理 XML,我必须在 ini 文件中显示数据。 IT 应该有像 [book] id=1 ef 这样的部分
-
book下有 2 个数组,每个数组都有一个id,因此在解析时,[book] id=2将覆盖id=1。我提供了 2 个选项,如果您需要其他内容,请提供一些反馈。
标签: php arrays multidimensional-array ini