我是PHP的新手,我试图从XML文件中获取数据并相应地显示它。 现在,我成功地提取了数据并进行了显示 以下是代码 -
if($xml_response = @simplexml_load_file('http://www.test.com/Testapp/TestSite?code=Test'))
{
foreach ($xml_response->promotions as $promotions) {
//print_r($promotions);
foreach ($promotions->promotion as $promotion) {
if(isset($promotion)){
$text=$promotion->text;
if (strlen($text) > 80) {
$stringCut = substr($text, 0, 80);
$text = substr($stringCut, 0, strrpos($stringCut, ' ')).' ... ';
}
?>
<div class="ads" style="margin-right:0px;">
<a href="<?=$promotion->link;?>" title="" target="_blank">
<h2><?php echo $promotion->title;?></h2>
<img src="<?php echo $promotion->image;?>" align="left" width="100px" height="80px">
<h2 style="vertical-align:text-top"><?php echo $text ?></h2></a>
</div>
<?php }
else
{?>
<div class="ads" style="margin-right:0px;">
<h2>Advertisement Title 1</h2>
<img src="images/side-banner.jpg" align="left" width="100px" height="80px">
<h2 style="vertical-align:text-top">We improve your way of working and communicating with your groups.</h2>
</div>
<?php } }
现在,我可以在内容存在时显示图像,但是当没有内容时,应该显示默认内容。所以我检查了isset
条件,但仍然无法显示默认图像。
下面是XML -
<promotions>
<promotion>
<title>Test</title>
<text>Sign off for limited time offer</text>
<link>NewCentrescdr.jpg</link>
<image>test.jpg</image>
<date>2013-07-16</date>
</promotion>
<promotion>
<title>Test</title>
<text>Test text</text>
<link>http://www.test.com</link>
<image>test.jpg</image>
<date>2013-09-28</date>
</promotion>
</promotions>
现在,根据XML中的促销数量,我想在页面中显示 only three
。如果没有促销,则显示默认促销。在上面的XML中只有2个促销,所以第三个应该是默认的。我怎么能这样做
答案 0 :(得分:0)
我建议将简化简化为最低限度的代码并从那里开始工作。
一旦它完成你想要它做的事情,从那里建立并添加HTML,CSS等。
代码:
$xml_response = simplexml_load_string($x); // assume XML in $x
// count <promotion>, but maximum is 3
$count = count($xml_response->promotion);
if ($count > 3) $count = 3;
// loop over <promotion>, echo it out
for ($i = 0; $i < $count; $i++) {
$promotion = $xml_response ->promotion[$i];
echo "$promotion->title<br />$promotion->text<br /><br />";
}
// if there are less than 3 <promotion>, echo out standard.
if ($count < 3) {
echo "Standard<br />Standard Promotion<br /><br />";
}