-3

I have an array of objects, each one just a string pair, like

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

and I want to convert it into XML like so:

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

I have no problem manually writing a function to do this, but it really feels like something that should be built into PHP, but I can't find it anywhere. Does some function exist, or should I just convert the data by writing my own function? Thanks!

Edit: A lot of people are suggesting a for loop and going through the array. That's kind of what I meant by "manually writing a function". I was just thinking that my situation is generic enough that PHP/SimpleXML may have a built-in function like

$xml->addContent($faq);

Which would do everything to parse the $faq variable and convert it to XML.

Dan Goodspeed
  • 3,484
  • 4
  • 26
  • 35

2 Answers2

1

Just iterate over $faq, then cast your stdClasses to an array to add single child element. Something like this:

$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();

Output:

<?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>
Federkun
  • 36,084
  • 8
  • 78
  • 90
0

Here is my answer but using arrays instead of classes.

Demo: 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();
?>
blazerunner44
  • 657
  • 8
  • 19