2015-10-04 62 views
-3

我有對象的數組,每個人只是一個字符串對,像轉換對象的數組到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循環,並通過數組。這就是我所說的「手動編寫函數」的意思。我只是在想,我的情況是通用的是PHP/SimpleXML的可能有一個內置的功能一樣

$xml->addContent($faq); 

這將盡一切解析$ FAQ變量,並將其轉換爲XML。

+0

嘗試'SimpleXML' http://php.net/manual/en/book.simplexml.php – blazerunner44

+0

我沒有和它說:「類stdClass的客體不能轉換爲字符串「 –

+0

你可以發佈你用於SimpleXML的代碼嗎? – blazerunner44

回答

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