代码之家  ›  专栏  ›  技术社区  ›  Tom Smykowski

如何在PHP中显示HTML中的XML?

  •  30
  • Tom Smykowski  · 技术社区  · 15 年前

    我有一个XML字符串:

    $string = 
    "
    <shoes>
        <shoe>
           <shouename>Shoue</shouename>
        </shoe>
    </shoes>
    ";
    

    希望在我的网站上显示如下:

    This is XML string content:
    <shoes>
        <shoe>
           <shouename>Shoue</shouename>
        </shoe>
    </shoes>
    

    所以我想这样做:

    • 现场,不在文本框中
    • 没有外部库、框架等。
    • 用适当的新行格式化
    • 用制表符格式化
    • 没有颜色等,只有文本

    那么,如何以简单明了的方式做到这一点呢?

    5 回复  |  直到 9 年前
        1
  •  61
  •   Chris    15 年前

    如果只需要(预先格式化的)字符串的纯文本表示,可以用HTML将其包装起来。 <pre/> 标签与使用 htmlentities 要退出角括号:

    <?PHP echo '<pre>', htmlentities($string), '</pre>'; ?>
        2
  •  6
  •   Sinan    15 年前

    你可以使用 htmlentities() , htmlspecialchars() 或者类似的功能。

        3
  •  6
  •   justastefan    15 年前

    应该是这样的:

    echo '<p>This is XML string content:</p>'
    echo '<pre>';
    echo htmlspecialchars($string);
    echo '</pre>';
    
        4
  •  1
  •   Frank Forte    11 年前

    如果它是simplexmlobject

    <pre>
    <?php
    echo htmlspecialchars(print_r($obj,true));
    ?>
    </pre>
    
        5
  •  1
  •   H.Tries    9 年前

    我搜索了一个稍微有颜色输出的解决方案:

    $escaped = htmlentities($content);
    $formatted = str_replace('&lt;', '<span style="color:blue">&lt;', $escaped);
    $formatted = str_replace('&gt;', '&gt;</span>', $formatted);
    echo "<pre>$formatted</pre>\n";