我正在尝试从API创建XML文件(在本例中为Instagram API)。 但我面临一个问题,因为我用forEach函数创建它。查看产品部分中的productName和productPrice属性:
<product productName="No Title" productID="001" thumbPath="http://IMAGE_URL" productPrice="0">
<details>
detail1
</details>
</product>
<product productName="Sushi Homemade " productID="002" thumbPath="http://IMAGE_URL" productPrice="50.000 ">
<details>
detail2
</details>
</product>
<product productName="Sushi Homemade " productID="003" thumbPath="http://IMAGE_URL" productPrice="50.000 ">
<details>
detail3
</details>
</product>
Value productName =“Sushi Homemade”和productPrice =“50.000”仅适用于productID =“002”。但为什么该值也填充到下一个productID&gt; = 002。
这是使用PHP创建xml的片段。也许我会错的:
<products>
<category categoryName="Instagram">
<?php foreach ($contents->data as $data) {
foreach($data->comments->data as $comment){
if(preg_match('/#title/', $comment->text)){
$komen = preg_replace('/#title/', '', $comment->text);
break;
} else { $komen = 'No Title'; }
}
foreach($data->comments->data as $comment){
if(preg_match('/#price/', $comment->text)){
$harga = preg_replace('/#price/', '', $comment->text);
break;
} else { $harga = '0'; }
}
echo '<product productName="'. $komen .'" productID="' . $data->id . '" thumbPath="' . $data->images->thumbnail->url . '" productPrice="'. $harga .'">
<details>
<![CDATA[
<img src="' . $data->images->low_resolution->url . '" width="100%"/>
' . $data->caption->text . '
]]>
</details>
</product>