如何在PHP中将XML转换为JSON



我想把一些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;
}
}

您的XML总是在那个结构中吗?试着写一个通用的XML到JSON转换器比为特定用例编写一个要困难得多.

如果总是相同,只需按名称从JSON结构中挑选出您需要的部分,并将它们放入您想要的任何结构的数组中。对于问题中给出的XML输入和JSON输出,代码如下所示:

$sx = simplexml_load_string($xml);
$output = [];
foreach ( $sx->Variable as $variable ) {
$output[] = [
'Name' => (string)$variable['Name'],
'Comment' => (string)$variable['Comment'],
'EvaluatedDefinition' => (string)$variable['EvaluatedDefinition'],
'#text' => (string)$variable
];
}
echo json_encode($output, JSON_PRETTY_PRINT);

注意,使用(string)告诉SimpleXML,您想要元素或属性的文本内容,而不是表示它的对象。

最新更新