【发布时间】:2015-02-22 01:12:31
【问题描述】:
我正在整理一个 xml 属性列表提要,联合组织将使用它来发布我们的列表。
我正在使用 Cakephp,但没有使用 Cakephp xml 工具。只是无法将输出格式化为我需要的格式。
所以我有一个非常简单的查询。 (为清楚起见,此处未包括许多字段)
$sql = "select
Listing.id as PropertyId,
Listing.address as StreetAddress,
Listing.title as Caption,
Listing.description as Description
from properties as Listing
limit 2";
$properties = $this->Property->query($sql);
然后进行一些清理并添加一些不在数据库中的属性。
for($i=0;$i<count($properties);$i++){
$properties[$i]['Listing']['StreetAddress'] = '<![CDATA['.$properties[$i]['Listing']['StreetAddress'].']]>';
$properties[$i]['Listing']['DescriptionLang'] = "x";
$properties[$i]['Listing']['Caption'] = '<![CDATA['.$properties[$i]['Listing']['Caption'].']]>';
$properties[$i]['Listing']['Description'] = '<![CDATA['.$properties[$i]['Listing']['Description'].']]>';
}
我正在使用这个函数来处理数组...
header("Content-type: text/xml; charset=utf-8");
$domtree = new DOMDocument('1.0', 'UTF-8');
$xmlRoot = $domtree->createElement("Listings");
$xmlRoot = $domtree->appendChild($xmlRoot);
foreach($properties as $p){
foreach ($p as $key=>$value){
$currentElement= $domtree->createElement($key);
$currentElement= $xmlRoot->appendChild($currentElement);
if(is_array($value))
{
foreach ($value as $k=>$v)
{
$currentElement->appendChild($domtree->createElement($k,$v));
}
}
}
}
echo $domtree->saveXML();
exit;
创建这个,这几乎是完美的:
<Listings>
<Listing>
<PropertyId>2</PropertyId>
<StreetAddress><![CDATA[243 E 7th Ave]]></StreetAddress>
<Caption><![CDATA[Wholesale Deal]]></Caption>
<Description><![CDATA[]]></Description>
<DescriptionLang>x</DescriptionLang>
</Listing>
<Listing>
<PropertyId>3</PropertyId>
<StreetAddress><![CDATA[3724 W Glenn Dr]]></StreetAddress>
<Caption><![CDATA[Wholesale Deal]]></Caption>
<Description><![CDATA[]]></Description>
<DescriptionLang>x</DescriptionLang>
</Listing>
</Listings>
输出看起来很棒...除了我需要做两件事。
1.) DescriptionLang 的标签需要如下,但是会导致问题...
<DescriptionLang value="en">
它不喜欢空格或引号。对于我尝试过的报价...
"
但这也像在教堂放屁一样。
更新:xml 规范不允许使用空格。所以我正在与辛迪加联系,看看他是否可以告诉我他们是如何摆脱无法完成的事情的。
2.) 但最重要的是 Caption 和 Description 元素需要像这样嵌套在 DescriptionLang 元素中...
<DescriptionLang value="en">
<Caption><![CDATA[ captionhere ]]></Caption>
<Description><![CDATA[ descriptionhere ]]></Description>
</DescriptionLang>
我尝试了更多疯狂的东西,我可以在此处包含这些内容。似乎我应该能够在清洁步骤中添加另一个级别,但没有。
当然可以在这里使用一些指导。
【问题讨论】:
-
“它不喜欢空格或引号”——当然不喜欢,因为
createElement只需要一个标签名称。您需要使用setAttribute在创建的 DOM 节点上设置属性。对于将Caption和Description嵌套到DescriptionLang中,使用您当前的方法,您需要创建一个额外的数组维度并使用一个额外的循环。 -
谢谢你的小花絮。这是我第一次使用 xml。现在至少我知道要搜索什么了。
标签: php mysql xml multidimensional-array nested-loops