我在stackoverflow中读到了其中一个问题,其中一个用户通过@Mifas和@Abhishek Madhani分享了这个链接,这很有效。
现在,我想将xml输出格式化为这样:
<Form xmlns="url" label="Home Visit Form" type="TextView" name="FormName">
<Field name="Category" label="FormType" value="Form1" type="TextView"/>
<Field type="Delimiter"/>
<Field name="ContractNumber" label="Contract number" value="3300000011" type="TextView"/>
<Field type="Delimiter"/>
<Field name="ClientName" label="Name of Client" value="Neplatic Neplaticovic" type="TextView"/>
<Field name="BirthDate" label="Birthday" value="1980-07-04" type="TextView"/>
<Field name="DueDate" label="Due Date" value="2014-07-24" type="TextView"/>
</Form>
但我不知道怎么做。
PHP:
header('Content-Type: text/xml');
$Form= array(
0 => array(
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:noNamespaceSchemaLocation' => 'http://homecredit.net/muchserver/ws/visit/types',
'label'=> 'Home Visit Form',
'type' => 'TextView',
'name' => 'HomeVisitForm'
),
1 => array(
'id' => '002',
'name' => 'Ijas',
'subjects' => array('Science','History','Social')
)
);
// creating object of SimpleXMLElement
$xml_Form = new SimpleXMLElement("<?xml version='"1.0'"?><Form></Form>");
array_to_xml($Form,$xml_Form); // function call to convert array to xml
print $xml_Form->asXML(); //saving generated xml file
// function defination to convert array to xml
function array_to_xml($Form, &$xml_Form) {
foreach($Form as $key => $value) {
$key = is_numeric($key) ? "Field$key" : $key;
(is_array($value))
? array_to_xml($value, $xml_Form->addChild("$key"))
: $xml_Form->addChild("$key","$value");
}
}
?>
上面PHP代码的输出:
<Form>
<Field0>
<xsi>http://www.w3.org/2001/XMLSchema-instance</xsi>
<noNamespaceSchemaLocation>url</noNamespaceSchemaLocation>
<label>Home Visit Form</label>
<type>TextView</type>
<name>HomeVisitForm</name>
</Field0>
<Field1>
<id>002</id>
<name>Ijas</name>
<subjects>
<Field0>Science</Field0>
<Field1>History</Field1>
<Field2>Social</Field2>
</subjects>
</Field1>
</Form>
嗨,你可能想复习一下这个位
(is_array($value))
? array_to_xml($value, $xml_Form->addChild("$key"))
: $xml_Form->addChild("$key","$value");
它可能是正确的,但不清楚它的书写方式。通常情况下,会分配值等。
$var = (is_array($value))
? array_to_xml($value, $xml_Form->addChild("$key"))
: $xml_Form->addChild("$key","$value");
或
if(is_array($value)){
array_to_xml($value, $xml_Form->addChild("$key")); //recursive
}else{
$xml_Form->addChild("$key","$value");
}
这可能对你没有帮助,但在我看来很糟糕。此外,但更重要的是,你正在尝试设置属性name="DueDate"
。但是,我在您的代码中没有看到对$xml_Form->addAttribute()
的调用。
http://php.net/manual/en/simplexmlelement.addattribute.php
也许你需要这样的东西,但我现在不能测试。
foreach($Form as $key => $value) {
$key = is_numeric($key) ? "Field$key" : $key;
//....
将上面的内容更改为类似的内容。
$child = $xml_Form->addChild("Field");
foreach($Form as $key => $value) {
$child->addAttribute($key, $value);
}
可能需要一些工作来弄清楚如何通过处理这个部分
'subjects' => array('Science','History','Social')