You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

文本转二进制PHP&HTML脚本无法正常运行求助

问题解决:文本转二进制脚本的输入框异常与提交无响应问题

核心问题分析

你的脚本出现两个问题的根源是未对输出的用户输入做HTML转义处理:当$input包含HTML特殊字符(比如<、>、"、&)时,直接在<textarea>中echo会破坏HTML标签结构,导致输入框渲染异常,甚至让表单的提交逻辑失效。

修复后的完整代码

<?php
// Initialize the input and binary variables
$input = '';
$binary = '';

// Check if the form has been submitted
if(isset($_POST['submit'])) {
    $input = $_POST['input'];

    // Convert the input text to binary
    for ($i = 0; $i < strlen($input); $i++) {
        $binary .= decbin(ord($input[$i])) . ' ';
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Text to Binary Converter</title>
</head>
<body>
    <form method="post">
        <label for="input">Enter text to convert:</label><br>
        <!-- 使用htmlspecialchars转义输出,避免破坏HTML结构 -->
        <textarea id="input" name="input" rows="4" cols="50"><?php echo htmlspecialchars($input); ?></textarea><br>
        <input type="submit" name="submit" value="Convert">
    </form>

    <?php if(!empty($binary)) { ?>
        <p>
            Binary conversion of "<?php echo htmlspecialchars($input); ?>":<br>
            <?php echo htmlspecialchars($binary); ?>
        </p>
    <?php } ?>
</body>
</html>

关键修复点

  • 所有输出到HTML中的PHP变量($input、$binary)都用htmlspecialchars()函数转义,确保特殊字符被转换为HTML实体(比如<转为&lt;),不会破坏页面结构。
  • 这个修改同时解决了输入框显示异常和提交无响应的问题,因为HTML结构恢复正常后,表单能正确渲染并触发提交逻辑。

额外优化建议

如果需要输出标准的8位二进制(当前decbin输出的是最短位数,比如字符"A"会输出"1000001",补全后是"01000001"),可以把转换逻辑改成:

$binary .= str_pad(decbin(ord($input[$i])), 8, '0', STR_PAD_LEFT) . ' ';

内容的提问来源于stack exchange,提问作者riots19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 03:07:24