When converting xml to json , several objects name change to "#attributes" - php

I read this article.
https://qiita.com/yasumodev/items/74a73ed4b3f1dd45edb8
And I did the same thing.
// XML(RSSなど)を取得
$strXml = file_get_contents("./doc.xml");
// XML⇒JSONに変換
$strJson = xml_to_json($strXml);
// 出力
echo $strJson;
//**********************************
// XML ⇒ JSONに変換する関数
//**********************************
function xml_to_json($xml)
{
// コロンをアンダーバーに(名前空間対策)
$xml = preg_replace("/<([^>]+?):([^>]+?)>/", "<$1_$2>", $xml);
// プロトコルのは元に戻す
$xml = preg_replace("/_\/\//", "://", $xml);
// XML文字列をオブジェクトに変換(CDATAも対象とする)
$objXml = simplexml_load_string($xml, NULL, LIBXML_NOCDATA);
// 属性を展開する
xml_expand_attributes($objXml);
// JSON形式の文字列に変換
$json = json_encode($objXml, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
// "\/" ⇒ "/" に置換
return preg_replace('/\\\\\//', '/', $json);
}
//**********************************
// XMLタグの属性を展開する関数
//**********************************
function xml_expand_attributes($node)
{
if($node->count() > 0) {
foreach($node->children() as $child)
{
foreach($child->attributes() as $key => $val) {
$node->addChild($child->getName()."#".$key, $val);
}
xml_expand_attributes($child); // 再帰呼出
}
}
}
But in this way , several objects name change to "#attributes".
I want the original object name here(T_T)
Please help me.

When you json_encode() XML with attributes, this will create the #attributes elements your getting. The only way round this is to remove them as you expand them. I've changed the routine, the first thing is that I've put the part that processes the attributes first, this ensures that the root node gets processed as well.
The main thing is that I've changed the way it works to use XPath to retrieve the attributes, this then encodes them as you have, but also allows you to remove the attribute from the original node (using unset($attribute[0]);)...
function xml_expand_attributes($node)
{
foreach ($node->xpath("#*") as $attribute) {
$node->addChild($node->getName()."#".$attribute->getName(), (string)$attribute);
unset($attribute[0]);
}
if($node->count() > 0) {
foreach($node->children() as $child)
{
xml_expand_attributes($child); // 再帰呼出
}
}
}

Related

I need a recursive php function to loop through a xml file

I'm trying to loop through a xml file and save nodes pared with it's value into an array (key => value). I also want it to keep track of the nodes it passed (something like array(users_user_name => "myName", users_user_email => "myEmail") etc.).
I know how to do this but there is a problem. All the nodes could have children and those children might also have children etc. so I need some sort of recursive function to keep looping through the children until it reaches the last child.
So far I got this:
//loads the xml file and creates simpleXML object
$xml = simplexml_load_string($content);
// for each root value
foreach ($xml->children() as $children) {
// for each child of the root node
$node = $children;
while ($children->children()) {
foreach ($children as $child) {
if($child->children()){
break;
}
$children = $node->getName();
//Give key a name
$keyOfValue = $xml->getName() . "_" . $children . "_" . $child->getName();
// pass value from child to children
$children = $child;
// no children, fill array: key => value
if ($child->children() == false) {
$parent[$keyOfValue] = (string)$child;
}
}
}
$dataObject[] = $parent;
}
The "break;" is to prevent it from giving me the wrong values because "child" is an object and not the last child.
Using recursion, you can write some 'complicated' processing, but the problem is loosing your place.
The function I use here passed in a couple of things to keep track of the name and the current output, but also the node it's currently working with. As you can see - the method checks if there are any child nodes and calls the function again to process each one of them.
$content = <<< XML
<users>
<user>
<name>myName</name>
<email>myEmail</email>
<address><line1>address1</line1><line2>address2</line2></address>
</user>
</users>
XML;
function processNode ( $base, SimpleXMLElement $node, &$output ) {
$base[] = $node->getName();
$nodeName = implode("_", $base);
$childNodes = $node->children();
if ( count($childNodes) == 0 ) {
$output[ $nodeName ] = (string)$node;
}
else {
foreach ( $childNodes as $newNode ) {
processNode($base, $newNode, $output);
}
}
}
$xml = simplexml_load_string($content);
$output = [];
processNode([], $xml, $output);
print_r($output);
This prints out...
Array
(
[users_user_name] => myName
[users_user_email] => myEmail
[users_user_address_line1] => address1
[users_user_address_line2] => address2
)
With this implementation, there are limitations to the content - so for example - repeating content will only keep the last value (say for example there were multiple users).
You'll want to use recursion!
Here's a simple example of recursion:
function doThing($param) {
// Do what you need to do
$param = alterParam($param);
// If there's more to do, do it again
if ($param != $condition) {
$param = doThing($param);
}
// Otherwise, we are ready to return the result
else {
return $param;
}
}
You can apply this thinking to your specific use case.
//Using SimpleXML library
// Parses XML but returns an Object for child nodes
public function getNodes($root)
{
$output = array();
if($root->children()) {
$children = $root->children();
foreach($children as $child) {
if(!($child->children())) {
$output[] = (array) $child;
}
else {
$output[] = self::getNodes($child->children());
}
}
}
else {
$output = (array) $root;
}
return $output;
}
I'll just add to this
I've had some trouble when namespaces come into the mix so i made the following recursive function to solve a node
This method goes into the deepest node and uses it as the value, in my case the top node's nodeValue contains all the values nested within so we have to dig into the lowest level and use that as the true value
// using the XMLReader to read an xml file ( in my case it was a 80gig xml file which is why i don't just load everything into memory )
$reader = new \XMLReader;
$reader->open($path); // where $path is the file path to the xml file
// using a dirty trick to skip most of the xml that is irrelevant where $nodeName is the node im looking for
// then in the next while loop i skip to the next node
while ($reader->read() && $reader->name !== $nodeName);
while ($reader->name === $nodeName) {
$doc = new \DOMDocument;
$dom = $doc->importNode($reader->expand(), true);
$data = $this->processDom($dom);
$reader->next($dom->localName);
}
public function processDom(\DOMNode $node)
{
$data = [];
/** #var \DomNode $childNode */
foreach ($node->childNodes as $childNode) {
// child nodes include of a lot of #text nodes which are irrelevant for me, so i just skip them
if ($childNode->nodeName === '#text') {
continue;
}
$childData = $this->processDom($childNode);
if ($childData === null || $childData === []) {
$data[$childNode->localName] = $childNode->nodeValue;
} else {
$data[$childNode->localName] = $childData;
}
}
return $data;
}

Build an array as a tree structure from an XML file

I am trying to read this xml file, but the code I am trying to make should work for any xml-file:
<?xml version="1.0"?>
<auto>
<binnenkant>
<voorkant>
<stuur/>
<gas/>
</voorkant>
<achterkant>
<stoel/>
<bagage/>
</achterkant>
</binnenkant>
<buitenkant>
<dak>
<dakkoffer>
<sky/>
<schoen/>
</dakkoffer>
</dak>
<trekhaak/>
<wiel/>
</buitenkant>
</auto>
I am using the two functions below to turn the XML-file into an array and turn that array into a tree.
I am trying to keep the parent-child relationship of the XML file. All I am getting back from the second function is an array with all the tags in the xml-file.
Can someone please help me?
function build_xml_tree(array $vals, $parent, $level) {
$branch = array();
foreach ($vals as $item) {
if (($item['type'] == "open") || $item['type'] == "complete") {
if ($branch && level == $item['level']) {
array_push($branch, ucfirst(strtolower($item['tag'])));
} else if ($parent == "" || $level < $item['level']) {
$branch = array(ucfirst(strtolower($item['tag'])) => build_xml_tree($vals, strtolower($item['tag']), $level));
}
}
}
return $branch;
}
function build_tree ($begin_tree, $content_naam) {
$xml = file_get_contents('xml_files/' . $content_naam . '.xml');
$p = xml_parser_create();
xml_parse_into_struct($p, $xml, $vals, $index);
?>
<pre>
<?php
print_r($vals);
?>
</pre>
<?php
$eindarray = array_merge($begin_tree, build_xml_tree($vals, "", 1));
return $eindarray;
}
There are many classes which can load an XML file. Many of them already represent the file in a tree structure: DOMDocument is one of them.
It seems a bit strange that you want to make a tree as an array when you already have a tree in a DOMDocument object: since you'll have to traverse the array-tree in some way... why don't you traverse directly the tree structure of the object-tree for printing for example?
Anyway the following code should do what you're asking for: I've used a recursive function in which the array-tree is passed by reference.
It should be trivial at this point to arrange my code to better suit your needs - i.e. complete the switch statement with more case blocks.
the $tree array has a numeric key for each node level
the tag node names are string values
if an array follows a string value, it contains the node's children
any potential text node is threated as a child node
function buildTree(DOMNode $node = NULL, &$tree) {
foreach ($node->childNodes as $cnode) {
switch($cnode->nodeType) {
case XML_ELEMENT_NODE:
$tree[] = $cnode->nodeName;
break;
case XML_TEXT_NODE:
$tree[] = $cnode->nodeValue;
break;
}
if ($cnode->hasChildNodes())
buildTree($cnode, $tree[count($tree)]);
}
}
$source ='the string which contains the XML';
$doc = new DOMDocument();
$doc->preserveWhiteSpace = FALSE;
$doc->loadXML($source, LIBXML_NOWARNING);
$tree = array();
buildTree($doc, $tree);
var_dump($tree);

How to download STANDARD-XML metadata from RETS using PHRETS

Is there any solution to download STANDARD-XML metadata from RETS using PHRETS?
Currently am able to extract each class metadata as an array using PHRETS function GetMetadataTable and combining & converting to XML format.
But then recently I found difference in single STANDARD-XML metadata(of entire resources and classes) and individual class metadata. Using metadata viewer service RETSMD.com(built on PHRETS) also, the class name getting from STANDARD-XML metadata is different and unable to view the details.
Note: I got the STANDARD-XML metadata via direct browser log-in using credentials, like this
http://rets.login.url/GetMetadata?Type=METADATA-TABLE&Format=STANDARD-XML&ID=0
Anyone faced the same? Is there any solution using PHP?
Thanks in Advance!
I got a solution by modifying PHRETS library.
Added a new function there with following code,
if (empty($this->capability_url['GetMetadata'])) {
die("GetServerInformation() called but unable to find GetMetadata location. Failed login?\n");
}
$optional_params['Type'] = 'METADATA-SYSTEM';
$optional_params['ID'] = '*';
$optional_params['Format'] = 'STANDARD-XML';
//request server information
$result = $this->RETSRequest($this->capability_url['GetMetadata'], $optional_params );
if (!$result) {
return false;
}
list($headers, $body) = $result;
$xml = $this->ParseXMLResponse($body);
Note: Main thing to note is,
$optional_params['ID'] = '*';
Should be '*' instead '0'
If anyone is still unable to retrieve STANDARD-XML data from the CREA DDF data feed using PhRETS v2.x.x, I created a fork to the ./src/Parsers/Search/OneX.php file. You can add the following protected methods to the end of the file:
protected function parseDDFStandardXMLData(&$xml)
{
// we can only work with an array
$property_details = json_decode(json_encode($xml), true);
$retn = array();
if(! empty($property_details['RETS-RESPONSE']['PropertyDetails'])) {
foreach($property_details['RETS-RESPONSE']['PropertyDetails'] as $property_array) {
$retn[] = $this->parseArrayElements(null, $property_array);
}
}
return $retn;
}
protected function parseArrayElements($parent_key, $element)
{
// three possible $element types
// 1. scalar value
// 2. sub-array
// 3. SimpleXMLElement Object
$retn = array();
if(is_object($element)) {
$element = json_decode(json_encode($element), true);
}
if(is_array($element)) {
foreach($element as $node_key => $node) {
$key = $node_key;
if(! empty($parent_key)) {
$key = $parent_key . '|' . $key;
}
if(is_array($node) || is_object($node)) {
$nodes = $this->parseArrayElements($key, $node);
if(!empty($nodes)) {
foreach($nodes as $k => $n) {
$retn[$k] = $n;
}
}
}else{
$retn[$key] = $node;
}
}
}else{
$retn[$parent_key] = $element;
}
return $retn;
}
protected function parseRecordFromArray(&$array, Results $rs)
{
$r = new Record;
foreach($rs->getHeaders() as $key => $name) {
$r->set($name, $array[$name]);
}
return $r;
}
Then replace the parseRecords() method with:
protected function parseRecords(Session $rets, &$xml, $parameters, Results $rs)
{
if (isset($xml->DATA)) {
foreach ($xml->DATA as $line) {
$rs->addRecord($this->parseRecordFromLine($rets, $xml, $parameters, $line, $rs));
}
}elseif (isset($xml->{"RETS-RESPONSE"}->PropertyDetails)) {
$data = $this->parseDDFStandardXMLData($xml);
if(! empty($data)) {
$fields_saved = false;
foreach ($data as $line) {
if(!$fields_saved) {
$rs->setHeaders(array_keys($line));
}
$rs->addRecord($this->parseRecordFromArray($line, $rs));
}
}
}
}
The line, }elseif (isset($xml->{"RETS-RESPONSE"}->PropertyDetails)) { in the latter method does the trick to identify the STANDARD-XML RETS-RESPONSE node and parse the data.
Hope this helps,
Cheers!

Reading SOAP XML in PHP

I do a SOAP-call to my client. It returns a XML-document as a string (this is a workaround that I can't do anything about). I have the XML in a variable and I need to read this XML to grab the information I want.
I am looking for the fields DomesticCustomer, Addresses and GridOwner. I guess if someone helps me to get to the DomesticCustomer-part I can do the rest on my own.
Note: In this example, there is only one entry under each field, but there could be multiple, so I need to be able to foreach this.
Note #2: Because the client I use has some weird workaround for this to work, the response (the xml) is a simple string.
The XML is:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<MeteringPointIdResponse xmlns="http://www.ediel.no/schemas/public/nubix/MeteringPointIdResponse">
<RequestId xmlns="">3423424234</RequestId>
<Requestor xmlns="">
<GLN>234234234</GLN>
</Requestor>
<Customers xmlns="">
<DomesticCustomer>
<LastName>Name</LastName>
<FirstName>Name</FirstName>
<BirthDate>xxx-xx-xx</BirthDate>
<MeterNumber>xxxxx</MeterNumber>
<Addresses>
<Address>
<Address1>345345</Address1>
<PostCode>3514</PostCode>
<Location>xxxxxx</Location>
<CountryCode>xx</CountryCode>
<Installation>
<Description>xxxxx</Description>
<MeteringPointId>xxxxxxxxxxxxxxx</MeteringPointId>
<MeteringMethod>xxxxxx</MeteringMethod>
<InstallationStatus>xxxx</InstallationStatus>
<LastReadOffDate>xxxx-xx-xx</LastReadOffDate>
</Installation>
<GridOwner>
<GLN>xxxxxxx</GLN>
<Name>xxxxxxxx</Name>
<ProdatAddress>
<InterchangeRecipient>
<Id>xxxxxxx</Id>
<Qualifier>xx</Qualifier>
<Subaddress>xxxxx</Subaddress>
</InterchangeRecipient>
<Party>
<Id>xxxxxxxxxx</Id>
<CodeListResponsible>xxxx</CodeListResponsible>
</Party>
<EDISyntax>
<CharSet>xxx</CharSet>
<SyntaxId>xxxx</SyntaxId>
</EDISyntax>
<SMTPAddress>test#hey.com</SMTPAddress>
</ProdatAddress>
</GridOwner>
</Address>
</Addresses>
</DomesticCustomer>
</Customers>
</MeteringPointIdResponse>
</soap:Body>
</soap:Envelope>
If you use the built in library for php, it parses the response and returns a mixed object/array object that is INFINITELY easier to deal with than the xml
Edit: since you are using php's built in client, here is a simple class that I wrote built around it. It "flattens" the responce and makes it easy to retrieve responces like:
$soap = new SOAP($wsdl, $options);
$soap->call("stuff goes here");
$soap->find("what you are looking for goes here");
/**
* #author Troy Knapp
* #copyright 2011
*
* #version .1.1
*/
class Soap {
//***VARIABLES***//
var $request; //..............string; holds last soap request
var $requestHeaders; //.......string; holds the headers for the last request
var $response; //.............string; xml response
var $responseHeaders; //......string; holds the headers for the last response
var $result; //...............array; the soap response parsed into an array
var $wsdlLocation; //.........string; url for the wsdl
var $parameters; //...........array; saved array of parameters
var $function; //.............string; name of function to be accessed
var $findResult = array();
var $flatArray = array(); //..array; holds an easy to search array
//
//***OBJECTS***//
var $client; //...................instance of SoapClient
var $exception; //................obj; SoapFault exception object
//
//***DEFAULTS***//
public $options = array(
'trace' => 1
);
function __construct($wsdl, $options = false) {
if ($options == false) {
$options = $this->options;
} else {
$this->options = $options;
}
$this->wsdlLocation = $wsdl;
$this->client = new SoapClient($wsdl, $options);
}
/*
* Executes a given function when supplied the proper function name,
* parameters and options.
*/
function call($function, $parameters, $options=NULL) {
$this->function = $function;
$this->parameters = $parameters;
try {
//$this->response = $this->client->__soapCall($function, $parameters, $options);
$this->response = $this->client->$function($parameters, $options);
} catch (SoapFault $exception) {
$this->$exception = $exception;
}
//get info about the last request
$this->request = $this->client->__getLastRequest();
$this->requestHeaders = $this->client->__getLastRequestHeaders();
//more info about the last responce
$this->responseHeaders = $this->client->__getLastResponseHeaders();
//set up an easily searchable array of results
$this->flatten();
return $this->response;
}
/*
* Prints all kinds of interesting info about what went on for debugging
* purposes
*/
function printInfo() {
echo '<h2>SoapClient Info:</h2>';
echo 'wsdl location: ' . $this->wsdl_location . '<br/>';
echo 'SoapClient Options:';
echoPre($this->options);
echo '<h2>Call Info:</h2>';
echo 'Function Name: ' . $this->function . '<br/>';
echo 'Parameters: ';
echoPre($this->parameters);
echo '<h2>Last Request: <br></h2>';
echo $this->format($this->request);
echo '<h2>Request Headers: <br></h2>';
echo $this->format($this->requestHeaders);
echo '<h2>Last Response: <br></h2>';
echoPre($this->response);
echo '<h2>Response Headers: <br></h2>';
echo $this->format($this->responseHeaders);
}
/*
* Formats the xml to make it nice and purdy for display and debugging
* purposes
*/
function format($xml) {
// add marker linefeeds to aid the pretty-tokeniser (adds a linefeed between all tag-end boundaries)
$xml = preg_replace('/(>)(<)(\/*)/', "$1\n$2$3", $xml);
// now indent the tags
$token = strtok($xml, "\n");
$result = ''; // holds formatted version as it is built
$pad = 0; // initial indent
$matches = array(); // returns from preg_matches()
// scan each line and adjust indent based on opening/closing tags
while ($token !== false) :
// test for the various tag states
// 1. open and closing tags on same line - no change
if (preg_match('/.+<\/\w[^>]*>$/', $token, $matches)) :
$indent = 0;
// 2. closing tag - outdent now
elseif (preg_match('/^<\/\w/', $token, $matches)) :
$pad--;
// 3. opening tag - don't pad this one, only subsequent tags
elseif (preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)) :
$indent = 1;
// 4. no indentation needed
else :
$indent = 0;
endif;
// pad the line with the required number of leading spaces
$line = str_pad($token, strlen($token) + $pad, ' ', STR_PAD_LEFT);
$result .= $line . "\n"; // add to the cumulative result, with linefeed
$token = strtok("\n"); // get the next token
$pad += $indent; // update the pad size for subsequent lines
endwhile;
$result = highlight_string($result);
//nl2br(htmlentities($result));
return $result;
}
/*
* Searches the pre flattened array for a given key. If there is only one
* result, this will return a single value, if there are multiple results,
* it will return an array of values.
*
* #param string; $search - search for a response with this key
*/
function find($search=false) {
if ($search == false) {
return $this->flatArray;
} else {
if (isset($this->flatArray[$search])) {
$result = $this->flatArray[$search];
} else {
return false;
}
}
if(count($result)==1){
return $result[0];
}
else{
return $result;
}
}
/*
* This method flattens an array/object result into an array that is easy
* to search through. Search terms are set as keys with results set as
* arrays owned by said keys.
*/
function flatten($array=false) {
if ($array == false) {
$array = $this->response;
}
if (is_object($array)) {
//get the variables of object
$array = get_object_vars($array);
}
//howdy('array');
//echoPre($array);
//echo "_______________<br>";
if (is_array($array)) {
//loop through the sub elements and make sure they are arrays
foreach ($array as $key => $value) {
//if it's an object, we need to convert it to an array
if (is_object($value)) {
//get the variables of object
$value = get_object_vars($value);
}
//echo "key: $key value: ";
//echoPre($value);
//echo "_______________<br>";
//push the key=>value pairs to the flat array
if (!isset($this->flatArray[$key])) {
$this->flatArray[$key] = array();
}
array_push($this->flatArray[$key], $value);
if (is_array($value)) {
$this->flatten($value);
}
}
}
}
function getWSDL() {
$wsdl = file_get_contents($this->wsdlLocation);
}
}
It was that simple. Forgot to register the namespace.
$xml = simplexml_load_string($xml);
$xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
foreach ($xml->xpath('//DomesticCustomer') as $item)
{
print_r($item);
}
Use http://php.net/manual/en/class.soapclient.php (Proving your on PHP5)

PHP loads not wanted elements from a XML file

I wan't to load some data from my XML file using this function:
public function getElements()
{
$elements = array();
$element = $this->documentElement->getElementsByTagName('elements')->item(0);
// checks if it has any immunities
if( isset($element) )
{
// read all immunities
foreach( $element->getElementsByTagName('element') as $v)
{
$v = $v->attributes->item(0);
// checks if immunity is set
if($v->nodeValue > 0)
{
$elements[$v->nodeName] = $v->nodeValue;
}
}
}
return $elements;
}
I wan't to load that elements from my XML file:
<elements>
<element physicalPercent="10"/>
<element icePercent="10"/>
<element holyPercent="-10"/>
</elements>
I wan't to load only element node name and node value.
Got this code in my query loop:
$elements = $monster->getElements();
$elN = 0;
$elC = count($elements);
if(!empty($elements)) {
foreach($elements as $element => $value) {
$elN++;
$elements_string .= $element . ":".$value;
if($elC != $elN)
$elements_string .= ", ";
}
}
And finally - the output of $elements_string variable is wrong:
earthPercent:50, holyPercent:50, firePercent:15, energyPercent:5, physicalPercent:25, icePercent:30, deathPercent:30firePercent:20, earthPercent:75firePercent:20, earthPercent:75firePercent:20, earthPercent:75physicalPercent:70, holyPercent:20, deathPerce
It should rather return:
physicalPercent:10, icePercent:10, holyPercent:-10
Could you help me one more time?:)
Thank you in advance.
Well the XML-Parser doesn't magically know which elements you want to load and which you won't - you have to filter this by yourself. Then you have to decide where you want to filter your desired elements in the getElements-function you posted or in your "query loop" as you call it.
Should the getElements be some kind of general function which must return all elements? Then you should change that check if($v->nodeValue > 0) to something like if(!empty($v->nodeValue)) otherwise you wont get the "holyPercent" value since this is negative (and the old expression becomes false).
Then in your "query loop", just select your desired elements:
foreach($elements as $element => $value) {
if(in_array($element, array("physicalPercent", "icePercent", "holyPercent"))) {
$elN++;
$elements_string .= $element . ":".$value;
if($elC != $elN)
$elements_string .= ", ";
}
}
Just:
$xml = new SimpleXMLElement($xmlfile);
And then:
for($i=1;$i<Count($xml->elements);$i++)
echo $xml->elements[$i][0];
Didn't try if it works with [0], usually i use :
echo $xml->elements[$i]['attributename'];

Categories