【问题标题】:Converting an array of objects into XML将对象数组转换为 XML
【发布时间】:2015-10-04 15:35:48
【问题描述】:

我有一个对象数组,每个对象只是一个字符串对,比如

$faq[0]->{"question"} = "Here is my question 1";  
$faq[0]->{"answer"} = "Here is my answer 1";
$faq[1]->{"question"} = "Here is my question 2";  
$faq[1]->{"answer"} = "Here is my answer 2";

我想像这样将它转换成 XML:

<faq>
  <question>Here is my question 1</question>
  <answer>Here is my answer 1</answer>
</faq>
<faq>
  <question>Here is my question 2</question>
  <answer>Here is my answer 2</answer>
</faq>

我手动编写一个函数来做到这一点没有问题,但它确实感觉应该内置到PHP中,但我在任何地方都找不到它。是否存在某些函数,或者我应该通过编写自己的函数来转换数据?谢谢!

编辑:很多人建议使用 for 循环并遍历数组。这就是我所说的“手动编写函数”的意思。我只是在想我的情况足够通用,PHP/SimpleXML 可能有一个内置函数,比如

$xml->addContent($faq);

这将尽一切努力解析 $faq 变量并将其转换为 XML。

【问题讨论】:

  • 我做了,它说“stdClass类的对象无法转换为字符串”
  • 你能贴出你用于 SimpleXML 的代码吗?
  • 我尝试了几种不同的方法,最近我使用了this array_to_xml code,它在 $xml->addChild("$key","$value"); 上出错了行

标签: php xml


【解决方案1】:

只需遍历$faq,然后将您的stdClasses 转换为数组以添加单个子元素。像这样的:

$faqs = [];

$faqs[0] = new stdClass;
$faqs[0]->{"question"} = "Here is my question 1";  
$faqs[0]->{"answer"} = "Here is my answer 1";
$faqs[1] = new stdClass;
$faqs[1]->{"question"} = "Here is my question 2";  
$faqs[1]->{"answer"} = "Here is my answer 2";

$xml = new SimpleXMLElement('<faqs/>');
foreach ($faqs as $faq) {
    $xml_faq = $xml->addChild('faq');
    foreach ((array) $faq as $element_name => $element_value) {
        $xml_faq->addChild($element_name, $element_value);
    }
}

print $xml->asXML();

输出:

<?xml version="1.0"?>
<faqs>
    <faq>
        <question>Here is my question 1</question>
        <answer>Here is my answer 1</answer>
    </faq>
    <faq>
        <question>Here is my question 2</question>
        <answer>Here is my answer 2</answer>
    </faq>
</faqs>

【讨论】:

    【解决方案2】:

    这是我的答案,但使用数组而不是类。

    演示:http://blazerunner44.me/test/xml.php

    <?php
    header("Content-type: text/xml");
    $faq = array();
    $faq[0]['question'] = "Here is my question 1";  
    $faq[0]["answer"] = "Here is my answer 1";
    $faq[1]["question"] = "Here is my question 2";  
    $faq[1]["answer"] = "Here is my answer 2";
    
    $response = new SimpleXMLElement('<response></response>');
    
    foreach($faq as $block){
        $element = $response->addChild('faq');
        $element->addChild('question', $block['question']);
        $element->addChild('answer', $block['answer']);
    }
    
    echo $response->asXML();
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 2018-04-16
      • 1970-01-01
      • 2021-05-03
      • 2018-12-04
      • 2021-06-16
      相关资源
      最近更新 更多