doudao7511 2013-10-20 18:09
浏览 75
已采纳

PHP混合HTML和代码

(Preamble: Am new to PHP, coming from a C# background where I am used to very clean code. Am currently working on my own Wordpress site which has a purchased theme.)

I have seen this type of code in a WordPress theme:

<a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img src="<?php echo esc_url( $logo ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" id="logo"/></a>

I find this very hard to read compared to the refactored:

<?php
            echo '<a href="';
            echo esc_url( home_url( '/' ) ); 
            echo "><img src=";
            echo esc_url( $logo ); 
            echo " alt=";
            echo esc_attr( get_bloginfo( 'name' ) ); 
            echo '" id="logo"/></a>'
?>

But this is the easiest by far:

<?php
        get_anchor($url, $imgsource, $alt, $id);
?>

get_anchor being a custom function that echos an anchor configured according to the parameters.

But surely I am not the first to think of this. Are there any existing libs that have a set of functions that return properly formatted html like in this example? Is there something I am missing?

  • 写回答

3条回答 默认 最新

  • dongqu4443 2013-10-20 18:20
    关注

    I've written a function that returns a HTML tag based on the pure PHP output:

    function tag($name, $attrs, $content) {
        $res = '';
        $res .= '<' . $name;
        foreach($attrs as $key => $val)
            $res .= ' ' . $key . '="' . $val . '"';
    
        $res .= isset($content) ? '>' . $content . '</'.$name.'>' : ' />';
    
        return $res;
    }
    
    • $name is the tagname (e.g. a)
    • $attrs is a key, value array with attributes (e.g. array('href','http://google.com/'))
    • $content is the content / body of the tag (an other element or text)

    Example basic use:

    echo tag('a', array('href' => 'http://google.com/'),'Google');
    

    Example nested use with multiple children:

    echo tag('ul',array(),
            tag('li',array(),'one') . 
            tag('li',array(),'two') . 
            tag('li',array(),'three')
        );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)