【问题标题】:Var_dump() Displays String, echo()/print_r() Returns NothingVar_dump() 显示字符串,echo()/print_r() 无返回
【发布时间】:2016-06-15 10:11:41
【问题描述】:

我正在使用一个简单的 HTML DOM 解析器库来解析带有 DOCTYPE 标记的 URL。我能够达到所需的标签,但每当我回显或尝试存储结果时,它都不会显示任何内容。但是, var_dump() 向我显示了所需的字符串。

require_once("simpledom.php");

$url="http://google.com";
$sPage = file_get_contents($url);
$sPageContent = new simple_html_dom();
$sPageContent->load($sPage);
$sObjects = $sPageContent->find('unknown');

foreach($sObjects as $sKey)
{
    var_dump($sKey->_[4]); /*this var_dump shows the stuff */
    $showres = $sKey->_[4]
}

/* this variable should hold the string but it shows nothing */
echo $showres;

【问题讨论】:

  • var_dump 显示的类型是什么?
  • var_dump 显示字符串 '' (length=15)
  • 您是否尝试过在循环中回显,就像您正在执行 var_dump 一样?
  • 如果你只是在浏览器上回显,你什么都看不到...你到底想做什么?
  • 如果你想存储你在循环中解析的所有内容,你应该执行类似$showres .= $sKey->_[4]; 的操作。不知道这是否是所需的行为,请尝试通过编辑来澄清您的问题。就像你想要的输出一样......

标签: php html-parsing simple-html-dom


【解决方案1】:

当输出<!doctype html> 时,浏览器会将其作为元素读取,因此您需要对< 和> 符号进行编码。 PHP 已经为此构建了一个函数,http://php.net/manual/en/function.htmlspecialchars.php。

所以你的代码应该是:

echo htmlspecialchars($showres);

你的源代码中会给你什么

<!doctype html>

【讨论】:

    【解决方案2】:
    echo htmlentities($showres);
    

    将回显 $showres 中的内容并将所有 HTML 标记替换为 HTML 实体,这样您就可以看到字符串,而不会让浏览器将其用作标记。

    但不确定您要做什么。

    【讨论】:

      【解决方案3】:

      尝试将值转换为字符串

      $showres = (string)$sKey->_[4];
      

      此外,你的回声在你的循环之后

      【讨论】:

      • 这是一个字符串已经OP说; var_dump shows me string '<!doctype html>' (length=15) .
      • 对不起@David,它没有帮助
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 2015-01-05
      • 2015-05-29
      相关资源
      最近更新 更多