【问题标题】:How can I limit a string when parsing XML in PHP在 PHP 中解析 XML 时如何限制字符串
【发布时间】:2014-09-21 17:48:16
【问题描述】:

我正在用 PHP 编写一个自定义登录页面来解析 XML 产品提要。产品描述很长,因为涉及到技术信息和规格,所以需要压缩阅读前 200 个字符。希望在达到 200 个字符后有一个阅读更多链接。

我目前的代码是:

<?php

$xml = simplexml_load_file('feed.xml');

foreach ($xml->item as $item) { ?>
<div class="row">
<div class="lhs">
    <h3><a href="<?php echo $item->link ?>"><?php echo $item->brand.' '.$item->title ?></a></h3>
    <p class="pri">&pound;<?php echo $item->price ?></p>
    <p><?php echo $item->description; ?></p>
    </div>
    <div class="rhs">
        <img src="<?php echo $item->image_link ?>" alt="<?php echo $item->title ?>" height="150" />
        </div>
        </div>  

<?php
}
?>

请任何人建议我还需要添加什么?我可以遵循 PHP 的基本模式,我只需要一些指导。

非常感谢。

【问题讨论】:

    标签: php xml character limit feed


    【解决方案1】:

    注意 $short_description 行。 编辑了一些“显示更多”的基本 js 示例

    <?php
    $xml = simplexml_load_file('feed.xml');
    
    foreach ($xml->item as $item) {
        $short_description = substr($item->description, 0, 200);
        ?>
        <div class="row">
            <div class="lhs">
            <h3><a href="<?php echo $item->link ?>"><?php echo $item->brand . ' ' . $item->title ?></a></h3>
            <p class="pri">&pound;<?php echo $item->price ?></p>
            <p id="shown"><?php echo $short_description; ?>... <a href="#" onclick="document.getElementById('hidden').style.display = 'block'; document.getElementById('shown').style.display = 'none'; this.style.display = 'none'; return false;">Show more</a></p>
            <p id="hidden"><?php echo $item->description; ?></p>
            </div>
            <div class="rhs">
            <img src="<?php echo $item->image_link ?>" alt="<?php echo $item->title ?>" height="150" />
            </div>
        </div>  
    
        <?php
    }
    ?>
    

    【讨论】:

    • 谢谢六度。我没有选择使用 JavaScript,但效果很好。另一方面,我如何限制显示的结果数量,例如 10?还是我需要为此启动另一个线程?
    • 启动一个新线程可能会更好,但简单的解决方案是添加 $i = 0;在 foreach 之前。在 foreach 循环的最后添加 $i++;然后将这个条件放在循环内的某个地方: if($i === 10) { break; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多