php - foreach函数并动态更新xml文件

时间:2014-12-11 14:43:22

标签: php xml foreach

我使用此代码动态更新xml文件,

我的问题是我对如何应用行动的顺序感到困惑:

<?php

$files = scandir('./resources');
sort($files);
foreach($files as $file){
    if(is_dir("./resources/$file") and $file != "." && $file != ".."){
        myFun($file);
    }
}

$simplexml = simplexml_load_file('map.xml');

function myFun($scannedTitle){

    $tags = get_meta_tags('./resources/'.$scannedTitle.'/index.html');
    $scannedDescription = $tags['description'];


    $items = $simplexml->xpath('channel/item[@id="'.$scannedTitle.'"]');
    $items = $items[0];

    if($items->title[0] == $scannedTitle){

    }else{
        $items->title[0] = $scannedTitle;
    }

    if($items->description[0] == $scannedDescription){

    }else{
        $items->description[0] = $scannedDescription;
    }

}

$simplexml->saveXML("map.xml");

?>


代码工作正常,但现在我改变了函数的顺序,它不再起作用了。
我无法理解我必须执行哪些操作......

这里是我的&#34; map.xml&#34;文件:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
  <item id="red">
    <title>red</title>
    <link>http://website.com/resources/red/</link>
    <description>descriptionRed</description>
  </item>
  <item id="green">
    <title>green</title>
    <link>http://website.com/resources/green/</link>
    <description>Description of the green page.</description>
  </item>
  <item id="blue">
    <title>blue</title>
    <link>http://website.com/resources/blue/</link>
    <description>Description of the blue page.</description>
  </item>
</channel>
</rss>

1 个答案:

答案 0 :(得分:0)

您有一个变量范围问题myFun()将如何处理在函数外部创建的$simplexml

我认为通过在函数

中传递$simplexml的引用,它将以这种方式工作
 <?php
 $simplexml = simplexml_load_file('map.xml');

 $files = scandir('./resources');
 sort($files);
 foreach($files as $file){
     if(is_dir("./resources/$file") and $file != "." && $file != ".."){
         myFun($file, $simplexml);
     }
 }


 function myFun($scannedTitle, &$simplexml){

     $tags = get_meta_tags('./resources/'.$scannedTitle.'/index.html');
     $scannedDescription = $tags['description'];


     $items = $simplexml->xpath('channel/item[@id="'.$scannedTitle.'"]');
     $items = $items[0];

     if($items->title[0] == $scannedTitle){

     }else{
         $items->title[0] = $scannedTitle;
     }

     if($items->description[0] == $scannedDescription){

     }else{
         $items->description[0] = $scannedDescription;
     }

 }

 $simplexml->saveXML("map.xml");

 ?>