我在代码中遇到问题,当我解析XML到Array获取XML
的单个数组。实际上我想解析array / json中的所有soap v1.2响应消息。如果退出则获取多个数组,For例如,数组中的多个数据存在于数组中,并根据预期的输出包装单个数组。
这是我的代码:
data.txt文件
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="<a rel="nofollow" class="external free" href="http://schemas.xmlsoap.org/soap/envelope/">http://schemas.xmlsoap.org/soap/envelope/</a>"
xmlns="urn:enterprise.soap.sforce.com">
<soapenv:Body>
<getResponse>
<result xsi:type="sf:sObject">
<id>123</id>
<description>description</description>
<name>testing</name>
<cnic>23198398213</cnic>
</result>
<result xsi:type="sf:sObject">
<id>567</id>
<description>LOrem ipsum des</description>
<name>name testing</name>
<cnic>2827489024243</cnic>
</result>
</getResponse>
</soapenv:Body>
</soapenv:Envelope>
我的PHP代码:
<?php
ini_set("memory_limit", "44879M");
include("dom.php");
$xml = str_get_html( file_get_contents("data.txt") );
$final = array();
$result = $xml->find("result");
foreach($result as $r){
$tag = $r->children();
$one = array();
foreach($tag as $child){
$tag = $child->tag;
echo "<pre>";
print_r($tag); echo "<br>";
if( stristr($tag, ":") ){
list($com, $tag) = explode(":", $tag);
}
$one[$tag] = trim(strip_tags($child->innertext));
}
$final[] = $one;
}
print_r($final);
?>
我的预期输出应为:
Array
(
[getResponse] => Array(
[result]=> Array(
[0] => Array(
[id] => 123
[description] => description
[name] => testing
[cnic] => 23198398213
)
[1] => Array(
[id] => 567
[description] => LOrem ipsum des
[name] => name testing
[cnic] => 2827489024243
)
)
)
)
请帮忙
先谢谢。
答案 0 :(得分:1)
您最好使用递归解决方案将层次结构传递给数组。此代码从每个元素开始,如果有任何子节点,则它再次调用相同的例程来构建该子数据集的数据。
require_once "dom.php";
function xmlToArray ( simple_html_dom_node $base ) {
$newData = [];
foreach ( $base->children as $newElement ) {
if ( $newElement->has_child() === true ) {
$addData = xmlToArray($newElement);
// if element already exists
if ( isset($newData [ $newElement->tag ]) ) {
// if not already a list of elements
if ( !isset($newData [ $newElement->tag ][0])) {
// Turn into an array of elements
$newData [ $newElement->tag ] = [$newData [ $newElement->tag ]];
}
// Add data to end
$newData [ $newElement->tag ][] = $addData;
}
else {
$newData [ $newElement->tag ] = $addData;
}
}
else {
$newData [ $newElement->tag ] = $newElement->innertext;
}
}
return $newData;
}
$xml = str_get_html( file_get_contents("data.txt") );
$final = xmlToArray ( $xml->root->find("soapenv:Body")[0] );
print_r($final);
递归例程以<soapenv:Body>
标记的内容开始,然后处理此内容。
这输出......
Array
(
[getresponse] => Array
(
[result] => Array
(
[id] => 123
[description] => description
[name] => testing
[cnic] => 23198398213
)
)
)
我仍然建议使用SimpleXML或DOMDocument,但这应该适用于您已有的。