如何在PHP中动态构建<<< EOD字符串[关闭]
I want to build my string dynamically depending on the results from the DB. So far I have created something like this:
$feed = Some essential xml that needs to go here;
for ($a = 0; $a < count($images); $a++)
{
if ($a == 0)
{
$image_type = "Main";
}
else
{
$image_type = "PT". $a;
}
$feed += <<<EOD
<Message>
<MessageID>1</MessageID>
<OperationType>Update</OperationType>
<ProductImage>
<SKU>{$data['sku']}</SKU>
<ImageType>{$image_type}</ImageType>
<ImageLocation>{$images[$a]}</ImageLocation>
</ProductImage>
</Message>
EOD;
}
$feed += <<<EOD
</AmazonEnvelope>
EOD;
echo $feed;
This example of course returns nothing however I wanted to present my code in the way that I would like it to work. Do would I build the $feed string dynamically in this case?
我想根据数据库的结果动态构建我的字符串。 到目前为止,我已经创建了这样的东西: p>
$ feed =需要去的一些必要的xml;
for($ a = 0; $ a&lt; count( $ images); $ a ++)
{
if if($ a == 0)
{
$ image_type =“Main”;
}
else
{
$ image_type =“PT”。 $ a;
}
$ feed + =&lt;&lt;&lt;&lt; EOD
&lt;消息&gt;
&lt;消息ID&gt; 1&lt; /消息ID&gt;
&lt; OperationType&gt;更新&lt; / OperationType&gt;
&lt; ; ProductImage&gt;
&lt; SKU&gt; {$ data ['sku']}&lt; / SKU&gt;
&lt; ImageType&gt; {$ image_type}&lt; / ImageType&gt;
&lt; ImageLocation&gt; {$ images [$ a ]}&lt; / ImageLocation&gt;
&lt; / ProductImage&gt;
&lt; / Message&gt;
EOD;
}
$ feed + =&lt;&lt;&lt; EOD
&lt; / AmazonEnvelope&gt;
EOD;
echo $ feed;
code> pre>
这个例子当然没有返回任何内容,但我希望以我希望的方式呈现我的代码。 在这种情况下,我会动态构建$ feed字符串吗? p>
div>
In PHP string concatenation is done with the .
operator, not the +
. Therefore concatenate and assign is also .=
, not +=
. Fix that in both relevant lines and it'll work fine.
The underlying reason for the different operator here is that, unlike most other popular languages, PHP is weak-typed. The +
operator is as such reserved for mathematical operations, so PHP can handle these 2 different lines 'correctly':
echo '123'+'123'; // Shows 246
echo '123'.'123'; // Shows 123123