dongtou2097 2013-03-04 18:09
浏览 112
已采纳

将php变量内容转换为html字符串

I am parsing data from html using PHP Simple HTML DOM parser.

$html = file_get_html('www.example.com');
$e= $html->find('div[class=BodyContent]');

The variable $e contains html data (divs, imgs, etc). If I echo it on the screen with a foreach loop, it prints out on the screen perfectly. How can I convert this $e to a string? My goal is for it to look like this and use:

$x = str_get_html('<div id="BodyContent">Hello</div>
                   <div id="world">World</div>...otherData');

How can I do this so $e content displays as regular HTML inside str_get_html?

Update: The variable $e should contain HTML data after parsing:

<div id="BodyContent">
  <div id="somethingelse>
    <p>Some more content</p><a>Some links</a>
  <span></span>
</div>

The function from SimpleHtmlDom requires parameter 1 to be a string so...I want to convert the variable $e to a string so all these divs and paragraphs can be inserted into the str_get_html('HERE').

  • 写回答

1条回答 默认 最新

  • douganbi7686 2013-03-04 18:19
    关注

    $e is an array or an object. Casting it to an array will ensure you can implode on it even if its a single object, then implode will call the __toString on all the objects giving you a single html string:

    $htmlstr = implode("
    ", (array) $e);
    

    The array casting could be overkill because in order to get just a single object as the return value from find you have to call it with a specific index - so presumably you would know whether to cast or not... but if you are juggling $e around a bunch it might be easier to just cast it like ive show so it doesnt blow up.

    In that case you need to find the Method you want in the API and call it on each element... Id use array_map for this:

    $htmlstr = implode("
    ", array_map(function ($node) { return $node->whatever; }), (array) $e);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了