【问题标题】:Converting a returned PHP file to XML将返回的 PHP 文件转换为 XML
【发布时间】:2013-10-18 18:23:21
【问题描述】:

我正在寻找一种使用 PHP 脚本将我从网站检索到的 PHP 文件转换为 XML 格式的方法。

我得到的返回文件是:

    { "days": [ 
    {"reference":"13L6-A67-1", "dayinit":"4","hourinit":"9"},
    {"reference":"13L6-A67-1", "dayinit":"5","hourinit":"9"} ]}

无论如何我可以将其转换为这样的 XML 文件:

    <?xml version="1.0"?>
    <days>
        <day>
            <lesson>
                <reference>13L6-A67-1</reference>
                <hourinit>9</hourinit>

            </lesson>
        </day>
        <day>
            <lesson>
                <reference>13L6-A67-1</reference>

                <hourinit>9</hourinit>

            </lesson>
        </day>
    </days>

最好是根据“dayinit”对数据进行分组。

【问题讨论】:

  • 问问自己:如何在 PHP 中创建 HTML? HTML 与 XML 非常相似。
  • 第一个文件不是 PHP,而是 JSON。
  • 使用 json_decode 将文件转换为数组,然后使用 XML 库从中创建所需的 XML 元素。

标签: php html xml parsing html-parsing


【解决方案1】:

您检索的是写在JSON 中的内容。您可以尝试使用 PHP 原生函数来转换您的内容。以下示例是您如何处理您的解决方案的粗略说明。

首先,获取并解码 JSON (documentation):

$json = '...'; // JSON content
$data = json_decode($json, true);

然后,使用 XML Parser (documentation) 将您的 $data 呈现为 XML:

// Something like
$xml_parser = xml_parser_create();
xml_parse($xml_parser, $data);

【讨论】:

    【解决方案2】:

    您可以将数据转换为数组并循环遍历它:

    $test_array = json_decode('{ "days": [
    {"reference":"13L6-A67-1", "dayinit":"4","hourinit":"9"},
    {"reference":"13L6-A67-1", "dayinit":"5","hourinit":"9"} ]}',true);
    
    $xml = '<?xml version="1.0"?>';
    $xml .= '<days>';
    
    foreach($test_array['days'] as $day) {
        $xml .= '<day>';
            $xml .= '<lesson>';
                $xml .= '<reference>';
                    $xml .= $day['reference'];
                $xml .= '</reference>';
                $xml .= '<dayinit>';
                    $xml .= $day['reference'];
                $xml .= '</reference>';
                $xml .= '</dayinit>';
                    $xml .= $day['hourinit'];
                $xml .= '</hourinit>';
            $xml .= '</lesson>';
        $xml .= '</day>';
    }
    
    $xml .= '</days>';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      • 2016-02-20
      • 1970-01-01
      相关资源
      最近更新 更多