将对象数组转换为XML

时间:2015-10-04 15:35:49

标签: php xml

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

$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循环并通过数组。我的意思是&#34;手动编写一个函数&#34;。我只是认为我的情况足够通用,PHP / SimpleXML可能有像

这样的内置函数
$xml->addContent($faq);

将解析$ faq变量并将其转换为XML。

2 个答案:

答案 0 :(得分:1)

只需迭代$faq,然后将stdClass es转换为数组以添加单个子元素。像这样:

$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>

答案 1 :(得分:0)

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

演示: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();
?>