Php 当要显示的内容不存在时,如何显示默认div
我是PHP新手,我试图从XML文件中获取数据并相应地显示它。 现在,我成功地提取并显示了数据。Php 当要显示的内容不存在时,如何显示默认div,php,xml,Php,Xml,我是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);
以下是守则-
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 } }
现在,根据XML中的促销数量,我只想在页面中显示三个。如果没有升级,则显示默认升级。在上面的XML中,只有两个升级,所以第三个升级应该是默认升级。如何满足此条件我建议将其简化为最低限度的代码,并从那里开始工作。
一旦它完成了您想要它做的事情,就从那里开始构建并添加HTML、CSS等 代码:
$xml\u response=simplexml\u load\u string($x);//假设XML为$x
//计数,但最大值为3
$count=count($xml\u响应->升级);
如果($count>3)$count=3;
//绕过去,回音
对于($i=0;$i<$count;$i++){
$promotion=$xml_response->promotion[$i];
回显“$promotion->title
$promotion->text
”;
}
//如果少于3个,则回显标准。
如果($count<3){
回音“标准
标准推广
”;
}
看到它工作了吗
<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_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 />";
}