2016-03-10 47 views
0

我想解析一個XML文件。我想創建一個項目對象,其中包含標題,日期,版本以及包含項目中所有文件的文件數組等實例。一切似乎都起作用,如標題,日期和版本。php - 用數組創建對象

我通過打印出來查看結果進行檢查。但是,當我嘗試打印數組以查看內容是否正確時,沒有任何反應。我不確定我要去哪裏錯。

<?php 

require_once('project.php'); 
require_once('files.php'); 


function parse() 
{ 
    $svn_list = simplexml_load_file("svn_list.xml"); 
    $dir = $svn_list->xpath("//entry[@kind = 'dir']"); 


    foreach ($dir as $node) { 
     if (strpos($node->name, '/') == false) { 

      $endProject = initProject($node); 

     } 
    } 

    for ($x = 0; $x <= 7; $x++) { 
     echo $endProject->fileListArray[$x]->name . "<br />\r\n"; 
    } 

} 

function initProject($node){ 

    $project = new project(); 
    $project->title = $node->name; 
    $project->date = $node->commit->date; 
    $project->version = $node->commit['revision']; 

    initFiles($node,$project); 

    return $project; 

} 

function initFiles($project){ 

    $svn_list = simplexml_load_file("svn_list.xml"); 
    $file = $svn_list->xpath("//entry[@kind ='file']/name[contains(., '$project->title')]/ancestor::node()[1]"); 
    //$file = $svn_list->xpath("//entry[@kind='file']/name[starts-with(., '$project->title')]/.."); 

    foreach($file as $fileObject){ 
     $files = new files(); 
     $files->size = $fileObject->size; 
     $files->name = $fileObject->name; 
     array_push($project->fileListArray, $files); 
    } 

} 

echo $endProject->fileListArray打印出「陣列」7次。但是echo $endProject->fileListArray[$x]->name不打印任何東西。

我不確定數組是不是正在被初始化,或者如果我不正確地解析XML文件。

<?xml version="1.0" encoding="UTF-8"?> 
<lists> 
<list 
     path="https://subversion...."> 
    <entry 
      kind="file"> 
     <name>.project</name> 
     <size>373</size> 
     <commit 
       revision="7052"> 
      <author></author> 
      <date>2016-02-25T20:56:16.138801Z</date> 
     </commit> 
    </entry> 
    <entry 
      kind="file"> 
     <name>.pydevproject</name> 
     <size>302</size> 
     <commit 
       revision="7052"> 
      <author></author> 
      <date>2016-02-25T20:56:16.138801Z</date> 
     </commit> 
    </entry> 
    <entry 
      kind="dir"> 
     <name>Assignment2.0</name> 
     <commit 
       revision="7054"> 
      <author></author> 
      <date>2016-02-25T20:59:11.144094Z</date> 
     </commit> 
    </entry> 

回答

0

你的函數定義:

function initFiles($project) 

你的函數調用:

initFiles($node, $project); 

因此,該功能使用$node作爲$project,但$node沒有->fileListArray屬性數組,所以你array_push()失敗。

而且,在未來,不要忘記激活錯誤在我們的PHP代碼檢查

error_reporting(E_ALL); 
ini_set('display_errors', 1); 

錯誤檢查,你的原碼輸出這樣的錯誤:

PHP Warning: array_push() expects parameter 1 to be array, object given in ...

0

默認情況下,函數參數通過值,這意味着該參數的值不會卡在功能之外的變化,除非您通過引用傳遞。該PHP docs有更多的細節,但我認爲,如果你只是改變:

function initFiles($project){...到​​(注意&),因爲你希望它會工作。

+0

沒有。對象總是被傳遞以供參考。 – fusion3k