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 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛