【问题标题】:from xml to json formatting从 xml 到 json 格式
【发布时间】:2012-11-19 10:15:35
【问题描述】:

您好,我需要一些帮助,我有以下代码

    $producers = simplexml_import_dom($xmlDoc);
    $file = fopen('producers.json','w');
    foreach( $producers as $producer)
    {
       $info[] = $producer; 
    }
    $jsonInfo = json_encode($info);
    fwrite($file, $jsonInfo);
    fclose($file);

这个输出

[{"id":"8","name":"Em\u00e5mejeriet","street":"Grenv\u00e4gen 1-3\n\t\t\t\t\t","postal ":" 577 39\n\t\t\t\t\t","city":" Hultsfred\n\t\t\t\t","weburl":"http://www.emamejeriet. se","logourl":"http://172.16.206.1/~thajo/1DV449/laboration01/producer/images/ema.png"},{"id":"57","name":"\u00d6lands \ u00f6rtag\u00e5rd","street":" Stora Fr\u00f6 2393 \n\t\t\t\t\t","postal":" 380 62\n\t\t\t\t\t", "city":" M\u00f6rbyl...等等

我需要一些帮助来格式化它,我需要去掉换行符并将其格式化为更易读的 json 格式。我也无法让 UTF-8 工作。

/谢谢

【问题讨论】:

  • 在设置$info[]之前使用trim()函数
  • preg_replace('/[ ]{2,}|[\t]/', ' ', trim($data));

标签: php xml json domdocument


【解决方案1】:

试试这个:

PHP 5.4 提供 JSON_PRETTY_PRINT 选项以用于 json_encode() 调用。

http://php.net/manual/en/function.json-encode.php

$json_string = json_encode($data, JSON_PRETTY_PRINT);

 $string = '{"a":"apple","b":"banana","c":"catnip"}';
 $pattern = array(',"', '{', '}');
 $replacement = array(",\n\t\"", "{\n\t", "\n}");
 echo str_replace($pattern, $replacement, $string);

【讨论】:

  • 我让 JSON_PRETTY_PRINT 工作了,但是 preg 替换、修剪和 str_replace 都没有为文档做任何事情,可能是因为 $producer 是一个对象而不是字符串?
  • 我让它在我的代码中更早地工作,在那里我创建了 xml 文档,我修剪掉了空格并且它工作了,但我仍然无法弄清楚为什么编码不起作用..
  • 我使用 JSON_UNESCAPED_UNICODE 但不是像“name”:“Emåmejeriet”,而是在我的浏览器中得到“name”:“EmÃ¥mejeriet”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 2021-02-22
  • 2011-07-04
  • 1970-01-01
相关资源
最近更新 更多