【问题标题】:How to print to console from a php file in wordpress如何从wordpress中的php文件打印到控制台
【发布时间】:2016-01-20 19:58:06
【问题描述】:

我有一个 php 文件,它是 wordpress 插件的一部分。我需要调试我们遇到的问题。我想知道变量的值是什么。如何将变量的值打印到控制台?建议使用 echo 或 chrome 或 firefox 扩展。我无法让 echo 输出到控制台 (echo “$variablename";),也无法使用 firephp 的 firephp 扩展。

【问题讨论】:

  • 假设您不想将值直接转储到带有var_dump() 的页面上,为什么不使用file_put_contents() 将值输出到临时日志文件?

标签: php wordpress


【解决方案1】:

要回答您的问题,您可以这样做:

echo '<script>console.log("PHP error: ' . $error . '")</script>';

但我会建议做@Ishas 建议的事情之一。确保$error 不包含任何可能弄乱您的脚本的内容。

【讨论】:

    【解决方案2】:

    如果您正在考虑使用 javascript 控制台,则无法通过 PHP 执行此操作。

    您有几个选项可供选择:

    为了快速检查变量值,我会使用 var_dump,它还会显示变量的数据类型。当您请求页面时,这将输出到浏览器。

    【讨论】:

      【解决方案3】:

      在 WordPress 中从 PHP 登录到 DevTools 控制台

      在这里,您可以在 WooCommerce 中调试优惠券逻辑时查看我的实际问题解决方案。此解决方案仅用于调试目的。 (注意:截图不是最新的,也会暴露私有成员。)

      特点

      • 允许在渲染开始之前和之后打印
      • 在前端和后端工作
      • 打印任意数量的变量
      • 编码数组和对象
      • 公开对象的私有成员和受保护成员
      • 同时记录到日志文件
      • 在生产环境中安全轻松地选择退出(以防您继续通话)
      • 打印调用者类、函数和钩子(提高生活质量)

      解决方案

      wp-debug.php

      function console_log(): string {
          list( , $caller ) = debug_backtrace( false );
          $action = current_action();
          $encoded_args = [];
          foreach ( func_get_args() as $arg ) try {
              if ( is_object( $arg ) ) {
                  $extract_props = function( $obj ) use ( &$extract_props ): array {
                      $members = [];
                      $class = get_class( $obj );
                      foreach ( ( new ReflectionClass( $class ) )->getProperties() as $prop ) {
                          $prop->setAccessible( true );
                          $name = $prop->getName();
                          if ( isset( $obj->{$name} ) ) {
                              $value = $prop->getValue( $obj );
                              if ( is_array( $value ) ) {
                                  $members[$name] = [];
                                  foreach ( $value as $item ) {
                                      if ( is_object( $item ) ) {
                                          $itemArray = $extract_props( $item );
                                          $members[$name][] = $itemArray;
                                      } else {
                                          $members[$name][] = $item;
                                      }
                                  }
                              } else if ( is_object( $value ) ) {
                                  $members[$name] = $extract_props( $value );
                              } else $members[$name] = $value;
                          }
                      }
                      return $members;
                  };
      
                  $encoded_args[] = json_encode( $extract_props( $arg ) );
              } else {
                  $encoded_args[] = json_encode( $arg );
              }
          } catch ( Exception $ex ) {
              $encoded_args[] = '`' . print_r( $arg, true ) . '`';
          }
          $msg = '`?`, `'
              . ( array_key_exists( 'class', $caller ) ? $caller['class'] : "\x3croot\x3e" )
              . '\\\\'
              . $caller['function'] . '()`, '
              . ( strlen( $action ) > 0 ? '`?`, `' . $action . '`, ' : '' )
              . '` ➡️ `, ' . implode( ', ', $encoded_args );
          $html = '<script type="text/javascript">console.log(' . $msg . ')</script>';
          add_action( 'wp_enqueue_scripts', function() use ( $html ) {
              echo $html;
          } );
          add_action( 'admin_enqueue_scripts', function() use ( $html ) {
              echo $html;
          } );
          error_log( $msg );
          return $html;
      }
      

      wp-config.php(部分)

      // ...
      
      define( 'WP_DEBUG', true );
      
      // ...
      
      /** Include WP debug helper */
      if ( defined( 'WP_DEBUG' ) && WP_DEBUG && file_exists( ABSPATH . 'wp-debug.php' ) ) {
          include_once ABSPATH . 'wp-debug.php';
      }
      if ( ! function_exists( 'console_log' ) ) {
          function console_log() {
          }
      }
      
      /** Sets up WordPress vars and included files. */
      require_once( ABSPATH . 'wp-settings.php' );
      

      用法

      • 在呈现 HTML &lt;head&gt; 之前:
      console_log( $myObj, $myArray, 123, "test" );
      
      • HTML &lt;head&gt; 被渲染后(在模板等/上面不起作用时使用):
      echo console_log( $myObj, $myArray, 123, "test" );
      

      输出格式

      ? <caller class>\<caller function>() ? <caller action/hook>  ➡️  <variables ...>
      

      特别感谢

      【讨论】:

        【解决方案4】:

        你可以这样写一个实用函数:

        function prefix_console_log_message( $message ) {
        
            $message = htmlspecialchars( stripslashes( $message ) );
            //Replacing Quotes, so that it does not mess up the script
            $message = str_replace( '"', "-", $message );
            $message = str_replace( "'", "-", $message );
        
            return "<script>console.log('{$message}')</script>";
        }
        

        你可以这样调用函数:

        echo prefix_console_log_message( "Error Message: This is really a 'unique' problem!" );
        

        这将像这样输出到控制台:

        Error Message: This is really a -unique- problem!
        

        注意用“-”替换的引号。这样做是为了使消息不会像@Josef-Engelfrost 所指出的那样弄乱您的脚本

        你也可以更进一步,做这样的事情:

        function prefix_console_log_message( $message, $type = "log" ) {
        
            $message_types = array( 'log', 'error', 'warn', 'info' );
            $type          = ( in_array( strtolower( $type ), $message_types ) ) ? strtolower( $type ) : $message_types[0];
            $message       = htmlspecialchars( stripslashes( $message ) );
            //Replacing Quotes, so that it does not mess up the script
            $message = str_replace( '"', "-", $message );
            $message = str_replace( "'", "-", $message );
        
            return "<script>console.{$type}('{$message}')</script>";
        }
        

        然后像这样调用函数:

        echo prefix_console_log_message( "Error Message: This is really a 'unique' problem!" , 'error');
        

        会在控制台输出错误。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-06-05
          • 1970-01-01
          • 1970-01-01
          • 2021-08-26
          • 1970-01-01
          • 2013-12-22
          • 1970-01-01
          相关资源
          最近更新 更多