2016-03-10 45 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