【问题标题】:convert a php array to xml将php数组转换为xml
【发布时间】:2013-06-10 23:15:31
【问题描述】:

我有一个问题,这让我发疯了 2 天,我在 php 中有一个包含多个子表的关联数组,我想将其转换为 xml,尤其是 simplexml,但我认为我对所有重音都有问题特殊字符等他们告诉我更改编码“ISO-8859-1”,但它不起作用, 你能帮帮我吗。`

<?php
  header('Content-type: text/html');
  $xml_student_info = new SimpleXMLElement('<?xml version="1.0" encoding="ISO-8859-1" ?>');
// function defination to convert array to xml

  function array_to_xml($student_info, $xml_student_info) {
   foreach($student_info as $key => $value) {
    if(is_array($value)) {
        if(!is_numeric($key)){
            $subnode = $xml_student_info->addChild("$key");
            array_to_xml($value, $subnode);
        }
        else{
            array_to_xml($value, $xml_student_info);
        }
    }
    else {
        $xml_student_info->addChild($key,$value);
    }
}
return $xml_student_info; }
    //function call to convert array to xml
    echo array_to_xml($wall,$xml_student_info)->asXML();
     exit( ) ;

         ?>

请回答:

警告:SimpleXMLElement::__construct() [simplexmlelement.--construct]:实体:第 1 行:解析器错误:需要开始标记,在 C:\Program Files (x86)\EasyPHP-5.3 中找不到“

警告:SimpleXMLElement::__construct() [simplexmlelement.--construct]: ?> 在 C:\Program Files (x86)\EasyPHP-5.3.9\www\fbcnx.php 第 4 行

警告:SimpleXMLElement::__construct() [simplexmlelement.--construct]: ^ 在 C:\Program Files (x86)\EasyPHP-5.3.9\www\fbcnx.php 第 4 行

致命错误:在 C:\Program Files (x86)\EasyPHP-5.3.9\www\fbcnx.php:4 中未捕获的异常 'Exception' 带有消息 'String could not be parsed as XML' 堆栈跟踪:#0 C:\Program Files (x86)\EasyPHP-5.3.9\www\fbcnx.php(4): SimpleXMLElement->__construct('

【问题讨论】:

  • 这个错误表明 PHP 开头的标签不是预期的——这段代码来自 PHP 文件吗?

标签: php tabs


【解决方案1】:

SimpleXMLElement 构造函数中的?&gt; 导致了问题。您传递给类的构造函数的字符串需要是 XML 文档的根元素或 xml 文件的路径,请参阅http://www.php.net/manual/en/simplexmlelement.construct.php

【讨论】:

    【解决方案2】:
    $xml_student_info = new SimpleXMLElement('<?xml version="1.0" encoding="ISO-8859-1" ?>');
    

    SimpleXMLElement:__construct 需要格式良好的 XML 字符串。这应该有效:

    $xml_student_info = new SimpleXMLElement('<studentinfo/>');
    

    请注意,SimpleXML 始终接受 UTF-8 编码的字符串,而不是 ISO-8859-1 编码的字符串。如有必要,请使用 utf8_encode 将 ISO-8859-1 字符串转换为 UTF-8。

    如果生成的 XML 使用 ISO-8859-1 编码而不是 UTF-8 编码很重要,请保留 &lt;?xml ... ?&gt; 声明。

    【讨论】:

    • 我通过添加 修改了代码,但它给出了另一个错误警告:SimpleXMLElement::addChild() [simplexmlelement.addchild]: unterminated entity reference s_app=326914550570&s_uid=1509985731&said=1022&spid=1457&src= 101&t_link=app&t_ratio=1&t_story=FriendInterviewStory 在 C:\Program Files (x86)\EasyPHP-5.3.9\www\fbcnx.php 第 19 行
    猜你喜欢
    • 2011-12-25
    • 2015-09-03
    • 2016-10-03
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多