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

报告相同问题?