【发布时间】:2021-11-25 12:05:00
【问题描述】:
我想将 som xml 数据转换为一些漂亮的 json 数据,然后将其输出到 api 中。输出不是问题,而是 xml 数据的格式。我环顾四周,但还没有让它像那里的一些在线转换器那样漂亮。这是xml数据结构:
<?xml version="1.0" encoding="utf-8"?>
<CatapultVariableSet>
<Variable
Name="Email"
Comment=""
EvaluatedDefinition="info@yourcompany.com">info@yourcompany.com</Variable>
<Variable
Name="StreetAddress"
Comment=""
EvaluatedDefinition="1234 Lorem Ipsum Ave.">1234 Lorem Ipsum Ave.</Variable>
<Variable
Name="MiR_250"
Comment=""
EvaluatedDefinition="MiR250">MiR250</Variable>
</CatapultVariableSet>
**Into this pretty JSON data:**
[
{
"Name": "Email",
"Comment": "",
"EvaluatedDefinition": "info@yourcompany.com",
"#text": "info@yourcompany.com"
},
{
"Name": "StreetAddress",
"Comment": "",
"EvaluatedDefinition": "1234 Lorem Ipsum Ave.",
"#text": "1234 Lorem Ipsum Ave."
},
{
"Name": "MiR_250",
"Comment": "",
"EvaluatedDefinition": "MiR250",
"#text": "MiR250"
}
]
这个转换器可以做到:https://www.freeformatter.com/xml-to-json-converter.html#ad-output
但它是怎么做到的呢?我一直在寻找答案,但我的版本并不那么漂亮。这是我迄今为止尝试过的,以接近:
function my_awesome_func() {
$myfile = fopen("fildestination", "r") or die("Unable to open file!");
$output = fread($myfile,filesize("fildestination"));
fclose($myfile);
$json = json_encode($output);
$jsondecoded = json_decode($json, TRUE);
$simplexml = simplexml_load_string($jsondecoded);
$vars = $simplexml[0]->Variable;
$simpledecode = json_encode($simplexml, JSON_PRETTY_PRINT);
foreach($vars as $v){
$array = array(
"v_name" => $v["Name"][0],
"v_value" => $v["EvaluatedDefinition"][0]
);
$encodej = json_encode($array, JSON_PRETTY_PRINT);
echo $encodej;
}
}
【问题讨论】:
-
什么究竟不能使用给定的代码?您尝试过什么来解决问题?
-
您可以考虑使用SimpleXML 来读取您的xml 数据,然后对其进行json_encode。
-
它的工作范围扩大到它确实给了我一些 json 数据。但是,它的结构不是我想要的。这是上面代码的输出: { "v_name": { "0": "CompanyName" }, "v_value": { "0": "My Company, LLC" } }{ "v_name": { "0": "PhoneNumber" }, "v_value": null }{ "v_name": { "0": "MiR_250" }, "v_value": { "0": "MiR250" } }
-
“结构化”是什么意思?请通过编辑为您的问题添加所有说明