php - 准备好用作sitemap的数组(

时间:2016-07-14 05:32:32

标签: php arrays xml laravel

我想生成站点地图,所以我从我的数据库结果创建数组并将数组转换为xml,最后我将xml文件显示为站点地图。

这是我的代码:

首先,我从数据库中获取数据:

    $restaurantList = $DoctrineRestaurantRepo->getInformation();
    foreach ($restaurantList as $key => $value)
    {
        $resSlug = $restaurantList[$key]['restaurantSlug'];
        array_push($initialArray,  ["url"=>["loc" => $resSlug , "changefreq" =>"monthly" , "priority"=>"0.6"]]);
    }

结果如下:

array:102 [▼
  0 => array:1 [▼
    "url" => array:3 [▼
      "loc" => "example.com/jack"
      "changefreq" => "monthly"
      "priority" => "0.5"
    ]
  ]
  1 => array:1 [▼
    "url" => array:3 [▼
      "loc" => "example.com/alex"
      "changefreq" => "monthly"
      "priority" => "0.5"
    ]
  ]
  2 => array:1 [▼
    "url" => array:3 [▼
      "loc" => "example.com/anna"
      "changefreq" => "monthly"
      "priority" => "0.5"
    ]
  ]
  .
  .
  .
]

然后,我将其转换为xml:

$xml_template_info = new \SimpleXMLElement("<?xml version=\"1.0\"?><urlset></urlset>");

$this->array_to_xml($initialArray,$xml_template_info);
$xml_template_info->asXML(dirname(__FILE__)."/sitemap.xml") ;

public function array_to_xml(array $arr, \SimpleXMLElement $xml)
{
    foreach ($arr as $k => $v) {
        is_array($v)
            ? $this->array_to_xml($v, $xml->addChild($k))
            : $xml->addChild($k, $v);
    }
    return $xml;
}

xml文件如下所示:

<?xml version="1.0"?>
<urlset><0><url><loc>example.com/jack</loc><changefreq>monthly</changefreq><priority>0.6</priority></url></0><1><url><loc>example.com/alex</loc><changefreq>monthly</changefreq><priority>0.6</priority></url></1>....</102></urlset>

最后,我想显示xml:

header('Content-type: application/xml');
readfile(dirname(__FILE__)."/sitemap.xml");
exit();

实际上,我收到了一个错误:

enter image description here

我认为我的xml文件有误,我有两个问题:

1-我想从结果中删除密钥,所以我的xml文件应该是这样的:

<?xml version="1.0"?>
<urlset><url><loc>example.com/jack</loc><changefreq>monthly</changefreq><priority>0.6</priority></url><url><loc>example.com/alex</loc><changefreq>monthly</changefreq><priority>0.6</priority></url>....</urlset>

怎么做?

那个错误是什么意思?

0 个答案:

没有答案