0

I'm working on some system for a few hours now and this little thing is too much for me to think logically about at the moment. Normally I would wait a few hours but this is a last minute job and I need to finish this.

Here's my problem:

I have an XML file that gets posted to my PHP file, the PHP file inserts certain data into a DB, but some XML nodes have the same name:

<accessoires>
<accessoire>value1</accessoire>
<accessoire>value2</accessoire>
<accessoire>value3</accessoire>
</accessoires>

Now I want to get a var $acclist which contains all values seperated by a comma: value1,value2,value3,

I bet the solution to this is very easy but I'm at the known point where even the easiest piece of code becomes a hassle. And googling only comes up with nodes that in some way have their own identifiers.

Could someone help me out please?

4

2 回答 2

0

您可以尝试 simplexml_load_string 解析 html,然后在转换为数组后在节点上调用 implode。

注意此代码已在 php 5.4.6 中进行了测试,并按预期运行。

<?php
$xml = '<accessoires>
<accessoire>value1</accessoire>
<accessoire>value2</accessoire>
<accessoire>value3</accessoire>
</accessoires>';
$dat = simplexml_load_string($xml);
echo implode(",",(array)$dat->accessoire);

对于 5.3.x,我必须更改为

$xml = '<accessoires>
<accessoire>value1</accessoire>
<accessoire>value2</accessoire>
<accessoire>value3</accessoire>
</accessoires>';
$dat = simplexml_load_string($xml);
$dat = (array)$dat;
echo implode(",",$dat["accessoire"]);
于 2013-07-02T14:56:13.213 回答
-1

您可以通过使用能够解析和处理 XML 的库来做到这一点,例如使用SimpleXML

implode(',', iterator_to_array($accessoires->accessoire, FALSE));

这里的关键部分是使用iterator_to_array()SimpleXML 提供的同名子元素作为迭代器。否则$accessoires->accessoire,只会自动神奇地为您提供第一个元素(如果有)。

于 2013-07-03T03:53:55.850 回答