我正在尝试使用
XML
和 laravel
创建一个完整的 SimpleXMLElement
文件。
我读到我可以从关联数组构建这个文件,我正在尝试它。我需要创建这个
xml
来发送这个文件来发送 API。
但我的问题是,当我尝试构建我的文件时,返回此消息:
Call to undefined function App\Classes\array_to_xml()
为了创建我的文件,我构建了一个个性化的类,其中包含构建逻辑的任何方法。我要打电话给我的班级,所以:
$logalty = new Logalty();
$xml_user_info = new \SimpleXMLElement('<?xml version="1.0"?><user_info></user_info>');
$logalty->array_to_xml($allData, $xml_user_info);
当我调用我的函数时,返回之前的消息。
在我的班级
Logalty()
我有我的功能array_to_xml()
,其中包含:
public function array_to_xml($data, &$xml_user_info)
{
foreach($data as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml_user_info->addChild("$key");
array_to_xml($value, $subnode);
}else{
$subnode = $xml_user_info->addChild("item$key");
array_to_xml($value, $subnode);
}
}else {
$xml_user_info->addChild("$key",htmlspecialchars("$value"));
}
}
//creating object of SimpleXMLElement
$xml_user_info = new \SimpleXMLElement("<?xml version=\"1.0\"?><user_info></user_info>");
//function call to convert array to xml
array_to_xml($data, $xml_user_info);
//saving generated xml file
$xml_file = $xml_user_info->asXML('users.xml');
//success and error message based on xml creation
if($xml_file){
echo 'XML file have been generated successfully.';
}else{
echo 'XML file generation error.';
}
}
我不知道为什么要返回此消息。我尝试调用 $this->array_to_xml(),而不是调用 array_to_xml,但延迟太多。这是我第一次在 php 中使用 xml,我不太了解。
谢谢你的自述,抱歉我的英语不好
最后,我用这段代码解决了我的问题:
首先在我的控制器中,我更改对类的调用,而不是:
$logalty = new Logalty();
$logalty->array_to_xml($allData, $rootElement = null, $xml = null, $path);
在我的
class logalty()
public function array_to_xml($array, $rootElement = null, $xml = null, $path)
{
$_xml = $xml;
// If there is no Root Element then insert root
if ($_xml === null) {
//$_xml = new \SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>');
$_xml = new \SimpleXMLElement('<?xml version="1.0"?><installation_info></installation_info>');
}
// Visit all key value pair
foreach ($array as $k => $v) {
// If there is nested array then
if (is_array($v)) {
// Call function for nested array
$this->array_to_xml($v, $k, $_xml->addChild($k));
}else {
// Simply add child element.
$_xml->addChild($k, $v);
}
}
return $_xml->asXML($path.'/installation.xml');
这将返回我的 xml,并保存在我的文件夹中。我最初的问题是我正在执行一个没有意义的递归函数。