如何使用 SimpleXML 在 PHP 中合并两个 XML 文档?

发布于 2024-10-08 00:36:23 字数 625 浏览 0 评论 0原文

我有一个看起来像这样的数据库行。

ID (int):       123
Name (string):  SomeName
Data (string):  <data><foo>one</foo></bar>two</bar></data>

我需要按以下方式将此数据格式化为 XML。

<row>
  <id>123</id>
  <name>SomeName</name>
  <data>
    <foo>one</foo>
    <bar>two</bar>
  </data>
<row>

我目前正在使用 SimpleXML 尝试构建此文件,但我不确定如何将现有 XML 插入到我尝试构建的新 XML 文档中。

如果 PHP 附带了其他标准 XML 构建器,我也愿意使用它们。字符串连接不是一个可接受的答案。

编辑:看起来 SimpleXML 不能满足我的需要。我想此时我需要其他 XML 解析器的建议。

I have a database row that looks like this.

ID (int):       123
Name (string):  SomeName
Data (string):  <data><foo>one</foo></bar>two</bar></data>

I need to format this data as XML in the following way.

<row>
  <id>123</id>
  <name>SomeName</name>
  <data>
    <foo>one</foo>
    <bar>two</bar>
  </data>
<row>

I'm currently using SimpleXML to try to build this, but I'm not sure how to go about inserting the existing XML into the new XML document I'm trying to build.

If there are other standard XML builders that come with PHP, I'm open to using those, too. String concatenation is not an acceptable answer.

Edit: It looks as though SimpleXML won't do what I need. I guess at this point, I need suggestions for other XML parsers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我ぃ本無心為│何有愛 2024-10-15 00:36:23
$xml = new SimpleXMLElement('<row></row>');
$xml->addChild('id', /*database ID column*/);
$xml->addChild('name', /*database Name column*/);

$data = new SimpleXMLElement(/*database Data column*/);

$xml->addChild('data');
$xml->data->addChild('foo', $data->foo);
$xml->data->addChild('bar', $data->bar);

经过测试,它有效。将其转换为您的实际应用程序应该很简单。可能有更灵活的方法,但我不知道。他们称其为 SimpleXML 并不是无缘无故的:)

$xml = new SimpleXMLElement('<row></row>');
$xml->addChild('id', /*database ID column*/);
$xml->addChild('name', /*database Name column*/);

$data = new SimpleXMLElement(/*database Data column*/);

$xml->addChild('data');
$xml->data->addChild('foo', $data->foo);
$xml->data->addChild('bar', $data->bar);

Tested and it works. It should be trivial to convert this to your actual application. There may be a more flexible way of doing it, but I'm not aware of it. They don't call it SimpleXML for nothing :)

眼前雾蒙蒙 2024-10-15 00:36:23
$xml = '<data><foo>one</foo><bar>two</bar></data>'; // your data field

$row = new SimpleXMLElement('<row></row>'); // new row to inject your database fields into
$data = new SimpleXMLElement($xml); // new object from your xml data field

$row->id = '123'; // your id field
$row->name = 'Somename'; // your name field
$row->data->foo = $data->foo; // your foo record from your xml data field
$row->data->bar = $data->bar; // your bar record from your xml data field

$final_xml = $row->saveXML(); // restructure your xml file/string
echo $final_xml; // <?xml version="1.0"?><row><id>123</id><name>Somename</name><data><foo>one</foo><bar>two</bar></data></row>

测试了这段代码,它也有效。
您必须创建两个 SimpleXml 对象,如上面的答案。除此之外,您只需添加
其他元素,例如添加类变量。 将添加到最终的 xml 字符串/文件中。

不确定您是否需要
如果没有,您可以通过以下方式将其取出:

$final_xml = str_replace("<?xml version=\"1.0\"?>\n",'',$final_xml);

您可以查看 http://www. php.net/manual/en/simplexmlelement.asxml.php 了解有关将 SimpleXml 对象重新保存回 xml 字符串/文件的更多信息。

$xml = '<data><foo>one</foo><bar>two</bar></data>'; // your data field

$row = new SimpleXMLElement('<row></row>'); // new row to inject your database fields into
$data = new SimpleXMLElement($xml); // new object from your xml data field

$row->id = '123'; // your id field
$row->name = 'Somename'; // your name field
$row->data->foo = $data->foo; // your foo record from your xml data field
$row->data->bar = $data->bar; // your bar record from your xml data field

$final_xml = $row->saveXML(); // restructure your xml file/string
echo $final_xml; // <?xml version="1.0"?><row><id>123</id><name>Somename</name><data><foo>one</foo><bar>two</bar></data></row>

Tested this code and it also works.
You will have to create two SimpleXml Objects like the answer above. Other than that you can just add
additional elements like adding class vars. A <?xml version="1.0"?> will be added to the final xml string/file.

Not sure if you need the <?xml version="1.0"?>.
If not you can take it out with:

$final_xml = str_replace("<?xml version=\"1.0\"?>\n",'',$final_xml);

You can check out http://www.php.net/manual/en/simplexmlelement.asxml.php for more info on re-saving SimpleXml objects back to xml strings/files.

灯角 2024-10-15 00:36:23
/**
* Converts your record to XML.
* 
* @param array/object $record
* @return SimpleXMLElement
*/
function ConvertToXml($record){
    // Objects need to be arrays
    if(is_object($record)){
        $record = get_object_vars($record);
    }

    // We need an array argument
    if(!is_array($record)){
        trigger_error('$record must be an object or an array.', E_USER_WARNING);
        return null;
    }

    // Now we build XML
    ob_start();
    echo '<xml>', PHP_EOL;
    foreach($record as $name => $value){
        if(is_object($value) or is_array($value) or is_resource($value)){
            trigger_error('$record must have only scalar values.', E_USER_WARNING);
            return null;
        }
        if(!is_string($name) or !preg_match('~[a-z_][a-z0-9]*~i', $name)){
            trigger_error('$record must have only XML-tag friendly string keys.', E_USER_WARNING);
            return null;
        }

        // NULL produces an empty node
        if(is_null($value)){
            echo "<{$name} />", PHP_EOL;
            continue;
        }

        // Numerics don't need to be XML encoded
        if(is_integer($value) or is_float($value) or is_bool($value)){
            echo "<{$name}>{$value}</{$name}>", PHP_EOL;
            continue;
        }

        // We must have a string now
        if(!is_string($name)){
            trigger_error('$record must have only scalar values.', E_USER_WARNING);
            return null;
        }

        // Do we have an XML field?
        if(preg_match('~^\s*<.+>\s*$~s', $value)){
            // Test it for real!
            if($xml = @simplexml_load_string("<xml>{$value}</xml>")){
                echo $value, PHP_EOL;
                continue;
            }
        }

        // Now output random strings
        echo "<{$name}>", htmlentities($value, ENT_QUOTES, 'utf-8'), "</{$name}>", PHP_EOL;
    }
    echo '</xml>', PHP_EOL;

    // Store built XML
    $xml = ob_get_clean();

    // Load the built XML
    return @simplexml_load_string($xml);;
}

// Prepare an array
$record = array();
$record['ID'] = 1;
$record['Name'] = 'SomeName';
$record['Data'] = '<data><foo>one</foo><bar>two</bar></data>';
if($xml = ConvertToXml($record)){
    echo $xml->asXML();
}

^ 为后代提供答案。

/**
* Converts your record to XML.
* 
* @param array/object $record
* @return SimpleXMLElement
*/
function ConvertToXml($record){
    // Objects need to be arrays
    if(is_object($record)){
        $record = get_object_vars($record);
    }

    // We need an array argument
    if(!is_array($record)){
        trigger_error('$record must be an object or an array.', E_USER_WARNING);
        return null;
    }

    // Now we build XML
    ob_start();
    echo '<xml>', PHP_EOL;
    foreach($record as $name => $value){
        if(is_object($value) or is_array($value) or is_resource($value)){
            trigger_error('$record must have only scalar values.', E_USER_WARNING);
            return null;
        }
        if(!is_string($name) or !preg_match('~[a-z_][a-z0-9]*~i', $name)){
            trigger_error('$record must have only XML-tag friendly string keys.', E_USER_WARNING);
            return null;
        }

        // NULL produces an empty node
        if(is_null($value)){
            echo "<{$name} />", PHP_EOL;
            continue;
        }

        // Numerics don't need to be XML encoded
        if(is_integer($value) or is_float($value) or is_bool($value)){
            echo "<{$name}>{$value}</{$name}>", PHP_EOL;
            continue;
        }

        // We must have a string now
        if(!is_string($name)){
            trigger_error('$record must have only scalar values.', E_USER_WARNING);
            return null;
        }

        // Do we have an XML field?
        if(preg_match('~^\s*<.+>\s*$~s', $value)){
            // Test it for real!
            if($xml = @simplexml_load_string("<xml>{$value}</xml>")){
                echo $value, PHP_EOL;
                continue;
            }
        }

        // Now output random strings
        echo "<{$name}>", htmlentities($value, ENT_QUOTES, 'utf-8'), "</{$name}>", PHP_EOL;
    }
    echo '</xml>', PHP_EOL;

    // Store built XML
    $xml = ob_get_clean();

    // Load the built XML
    return @simplexml_load_string($xml);;
}

// Prepare an array
$record = array();
$record['ID'] = 1;
$record['Name'] = 'SomeName';
$record['Data'] = '<data><foo>one</foo><bar>two</bar></data>';
if($xml = ConvertToXml($record)){
    echo $xml->asXML();
}

^ An answer for posterity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文