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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站