doutan5844 2016-02-27 16:58
浏览 32
已采纳

通过数组迭代并使用PHP动态地将值添加到HTML

Using the code below, I am getting divs with class 'post' from an external HTML file and print them to the posts page. Everything shown below works as it should be, however I would like to supplement the code with some automation. More precisely, instead of having hard coded values in the arrays I want to pass variable which were obtained by iterating through all divs with the needed class. Could you please help to implement such action. Thanks in advance.

PHP

<?php

$doc = new DOMDocument();
$doc->loadHTMLFile($url);

$xpath = new DOMXpath($doc);

$post = $xpath->query("//*[contains(@class, 'post')]");

$array = iterator_to_array($post);
?>

HTML posts page

<div><?php  echo $doc->saveHTML($array[0]);?></div>
<div><?php  echo $doc->saveHTML($array[1]);?></div>
<div><?php  echo $doc->saveHTML($array[2]);?></div>

HTML external file

<div class="post">
    post 1 
</div>      
<div class="post">
    post 2 
</div>      
<div class="post">
    post 3
</div>
  • 写回答

1条回答 默认 最新

  • duanci9305 2016-02-27 17:05
    关注

    Not sure if i understood your question .. is this what u wanted ?

    foreach ($array as $key => $value)
     echo "<div> $value </div>";
    

    OR

    foreach ($array as $key => $value)
     echo "<div> ".$doc->saveHTML($value)." </div>";
    

    Update

    If you are looking for a function [Askd in comments]

    function printdiv($value){
     echo "<div> ".$doc->saveHTML($value)." </div>";
    }
    

    then call it from wherever you want eg. via foreach loop

    foreach ($array as $key => $value)
     printdiv($value);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开