phpinfo()输出结构来源及转div适配CSS Grid方法咨询
解决phpinfo()输出结构转为div适配CSS Grid的方法
首先明确:phpinfo()的HTML结构是PHP内核硬编码实现的,没有内置开关或配置能直接修改它的输出格式,你得通过捕获输出后转换结构的方式来实现需求。
方案1:捕获输出并替换HTML结构
利用PHP的输出缓冲功能,先把phpinfo()的输出抓下来,再通过字符串替换或DOM解析把table结构转换成div结构,具体步骤如下:
步骤1:捕获phpinfo()输出
用ob_start()开启输出缓冲,调用phpinfo()后用ob_get_clean()获取输出内容:
<?php ob_start(); phpinfo(); $phpinfo_html = ob_get_clean(); ?>
步骤2:转换table为div结构
这里给出简单的字符串替换示例(适合快速实现):
// 替换外层table为grid容器 $phpinfo_html = str_replace('<table border="0" cellpadding="3" width="600">', '<div class="phpinfo-grid">', $phpinfo_html); $phpinfo_html = str_replace('</table>', '</div>', $phpinfo_html); // 替换tr为行容器 $phpinfo_html = str_replace('<tr>', '<div class="phpinfo-row">', $phpinfo_html); $phpinfo_html = str_replace('</tr>', '</div>', $phpinfo_html); // 替换td/th为单元格 $phpinfo_html = str_replace(['<td>', '<th>'], '<div class="phpinfo-cell">', $phpinfo_html); $phpinfo_html = str_replace(['</td>', '</th>'], '</div>', $phpinfo_html); // 输出转换后的HTML echo $phpinfo_html;
如果需要更健壮的解析,可以用DOMDocument类遍历节点进行替换,避免字符串替换可能出现的匹配错误。
步骤3:添加CSS Grid样式
写对应的CSS让div结构适配Grid布局:
.phpinfo-grid { display: grid; gap: 1rem; padding: 1rem; max-width: 1200px; margin: 0 auto; } .phpinfo-row { display: grid; grid-template-columns: 200px 1fr; gap: 0.5rem; padding: 0.5rem; border-bottom: 1px solid #eee; } .phpinfo-cell { padding: 0.3rem; } /* 针对标题行做特殊处理 */ .phpinfo-row:first-child .phpinfo-cell { grid-column: 1 / -1; font-size: 1.2rem; font-weight: bold; }
方案2:自定义phpinfo展示(更灵活但繁琐)
如果字符串替换满足不了需求,你可以自己读取PHP配置信息,手动生成div结构。比如用ini_get_all()获取所有配置项,然后循环输出成Grid布局:
<?php $all_configs = ini_get_all(null, true); ?> <div class="phpinfo-grid"> <div class="phpinfo-row"> <div class="phpinfo-cell" style="grid-column: 1/-1;">PHP 配置信息</div> </div> <?php foreach ($all_configs as $section => $configs): ?> <div class="phpinfo-row"> <div class="phpinfo-cell" style="grid-column: 1/-1; font-weight: bold;"><?= $section ?></div> </div> <?php foreach ($configs as $key => $details): ?> <div class="phpinfo-row"> <div class="phpinfo-cell"><?= $key ?></div> <div class="phpinfo-cell"><?= $details['value'] ?></div> </div> <?php endforeach; ?> <?php endforeach; ?> </div>
这个方法能完全控制HTML结构,但无法获取phpinfo()里的编译参数、模块详细信息等额外内容,若需要这些信息,优先选方案1。
内容的提问来源于stack exchange,提问作者user4537352
相关产品推荐
相关产品推荐

