Add attributes to xml php

Creating a SOAP request with PHP — how do I add attributes to the XML tags?

I can create most of the call just fine — I’ve finally picked up that nested arrays are my friends — but I have no idea how to add those ID=»$int» and Action=»Apply» attributes to the various tags. I’m sure this is fairly easy, but I just can’t figure it out. TIA.

Just passing it as an argument in my SOAP function call. So, assuming $client is my SOAP handle, it’s $result = $client->NameOfFunction(array(whatever => whatever));

@benjy: You should not repost an unsolved question immediately, just edit/enhance the original if new stuff comes up. I answered here as this seems to be the original question and it has the better title.

4 Answers 4

You should be able to add attributes with following syntax:

array("foo" => array("_" => "cheese", "bar"=>"moo")); 

This should produce following XML

I had the same problem with the attributes and I ended up using XMLWriter as commented in this post: http://eosrei.net/articles/2012/01/php-soap-xml-attributes-namespaces-xmlwriter

$prefix = 'ns1'; $xml = new \XMLWriter(); $xml->openMemory(); $xml->startElementNs($prefix, 'SomeRequest', null); $xml->writeElementNs($prefix, 'SchemaVersion', null, "2.0"); $xml->startElementNs($prefix, 'SomeComplexType', null); $xml->writeElementNs($prefix, 'MessageId', null, 11); $xml->writeElementNs($prefix, 'Timestamp', null, '2013-07-05T14:43:43.649-04:00'); $xml->startElementNs($prefix, 'Authentication', null); $xml->writeAttribute('SomeAttribute', '12312'); $xml->writeElementNs($prefix, 'UserId', null, 'myUser'); $xml->writeElementNs($prefix, 'Password', null, 'somePass'); $xml->endElement(); $xml->endElement(); $xml->endElement(); $request = new SoapVar($xml->outputMemory(), XSD_ANYXML); $result = $this->call('submit', $request); 
    2.0 11 2013-07-05T14:43:43.649-04:00 myUser somePass      

I don’t know about the (somewhat weird) syntax suggested by JJ (and according to your reposting of the question, it doesn’t seem to work), but you should be able to shape your request xml anyway you want by constructing it more or less ‘manually’ using the SoapVar class with the XSD_ANYXML encoding.

If the XML you need to construct gets more complex, consider using SimpleXML or DOMDocument to assemble it instead of writing it directly.

(It still seems odd to me that there should be no simpler way to do this, but so far I have not found one.)

Edit: Just found another example using the XSD_ANYXML encoding in this question asking for a simpler way to do it. Unfortunately no one came up with a simpler way so far :/

I spend two nights with this topic while working on a german SOAP Webservice which allows town website to synchronize with a central database about all different kinds of Request they can convern from the goverment and where they have to go for this. The WSDL was very simple for years, there were no attributes when pushing back messages to this Webservice. We just build up objects with stdClass and gave them the according properties. like $stdClassObj->PROPERTY = ‘value’;

Then they started using an attributes for certain properties for multilanguage purposes and added a new Object called LocalizedText and all properties which are in multilange inherited from this property. Which is where those two long nights began, because I found ALOT of different «possibile» solutions for this «simple problem» and maybe some of them work depending on the complexity of the WSDL structure. However good luck if you read this and this URLS are still online: The WSDL: https://ws-mv-schul.zfinder.de/V6_30/?wsdl And theres is also a german documentation which is not even readfriendly when you know german but at least some kind of docs: https://ws-mv-schul.zfinder.de/doc/6_30/index.html

Читайте также:  Python interpreter step by step

As long as its online you maybe can connect to it to access some informations ( ->__getTypes() ), but you cant use the function without an authentification.

So I started my tries to push back informations to this API with the correct attributes and no soluation I found on the whole internet worked for me. Some say «just put an array into SoapVar» and it will recognize what to with it and maybe this works for simple Services but not in my case. Maybe it works on other solutions because they just include one namespace in the xsd:schema section but in my case there are serveral namespaces and also subincludes of other .xsd schemes which include even more namespaces and so on. Just putting an array in one of the SOAP Type properties or even an stdClass inside an SoapVar object just resulted in nested nodes instead of an attribute.

Expected Text resulted in <_>Textde_DE with arrays or simple objects inside or outside of SoapVar. I tried arrays and objects nested / not nested and in all other combinations and IT DID NOT WORK FOR ME! So once again all tries with arrays or stdClass like $soapObject->Property = [‘_’ => ‘Test’, ‘language’ => ‘de_DE’] or $soapObject->Property = new \SoapVar([‘_’ => ‘Test’, ‘language’ => ‘de_DE’], SOAP_ENC_OBJECT) or a

$property = new \stdClass(); $property->_ 'Test'; $property->language 'de_DE'; $soapObject->Property = new \SoapVar($property, SOAP_ENC_OBJECT) 

Resulted always in the wrong XML at submitting causing errors. The above mentioned solution by using SoapVar with property XSD_ANYXML set did work for me for testing purposes, but this was not a clean solutation for me because I just did not believe that this cannot work without creating an own XmlElement. Anyway I already started to loose my hope when I saw the answers here and on other platforms are getting older and older.

The SoapVar documentation on php.net is not explained at all, after the second construct argument like «SOAP_ENC_OBJECT» I did not understand what those parameters do and mean at all. I’m not working alot with strange XML markups so this is not my main area at developing — maybe others understand more conretly what those construct params do and mean and feel free to provide more details about everything of this:

public __construct( mixed $data, ?int $encoding, ?string $typeName = null, ?string $typeNamespace = null, ?string $nodeName = null, ?string $nodeNamespace = null ) 

Tried some different things with those params but nothing really worked and resulted in more or less more worse XML results.

Читайте также:  Convert svg to png php

Sorry telling you this long story but I just want you to know that googeling will result in alot of answers which say «this worked» or «this worked» and the conclusion is just: It depends on the WSDL complexcity.

So I also started thinking about creating alot of own new Classes and use the SoapClients $classmap itself but before started trying this I finally found the solution (when I was drunk): I knew it must work somehow with SoapVar and it does, without using the XSD_ANYXML way, but you must know how to configure your new \SoapVar() to build the correct XML. First of all: The SoapClient must be in WSDL mode, so provide the correct WDSL URI as first parameter when bulding SoapClient. For non-wsdl mode I guess only the XSD_ANYXML can work.

So in my case alot of properties always inherit from LocalizedText and are always the same so I created ONE namespaces class in my project which has the same properties like LocalizedText from WDSL.

I also gave the class the same name but I’m not sure if this is even necessary.

_ = $_; $this->language = $language; > > 

Then I started to create object like this and put them into SoapVar. still does NOT WORK. Then I provided the third parameter of SoapVar trying to tell the object what kind of property I want to provide: STILL DOES NOT WORK. In my case there are just to many nested kind of namespaces, «tns», inclusions of other .xsd schemes which even include more things and so on. So of course SoapVar / Client was not able to figure out what property I really want to provide which of course resulted in errors or bad XML.

Then finally I started to figure out more about «typeNamespace» (in the mentioned doc I saw tns: and I though its the same but tns: is according to W3C «this namespace», experts please provide more explanation here). So I got deeper and deeper inside the includes. Finally, maybe much to late saw xmlns:tns=»http://www.tsa.de/infodienste» in xsd:schema but always inside other xmls:xy but of course one thing in case of namespaces was always the same inside the includes: The URL «http://www.tsa.de/infodienste». Providing this url and of course EVEN IF THIS IS ONLY A URI, THIS IS A NAMESPACE WE NEED, to for SoapVar constructors constr parameter typeNameSpace almost brought the solution but still errors because I still provived $typeName to the name of each property like «foo», «bar» depending on which property my Algorithm is currently parsing. I dont know why this did not work for me but finally I stopped this and just said: All those properties are inherit from this «LocalizedText» (always debug for yourself $client->__getTypes() !) and have no other differences to each other (lucky in my case?) and then it finally started working by adding properties like this:

$property = new \Namespace\XY\LocalizedText( "value", 'de_DE' ); $soapObject->PROPERTY= new \SoapVar( $property, SOAP_ENC_OBJECT, 'LocalizedText', // In my case properties always inherit from this in WDSL 'http://www.tsa.de/infodienste' // Always the same in every schema or include ); 

I’m happy this works for me and even more for other people and if you read this and create SOAP Webservices yourself, feel free to provide additional tips and tricks about this or finally add a real documentation to SoapVar to php.net who are not working alot this stuff to save their lifetime 😉

Читайте также:  Css запрет контекстного меню

I wasted alot of time by «partially» understanding this instead of simply using XSD_ANYXML, important for my education but I still dont feel safe about the other params of SoapVar.

Источник

simple xml add attribute

Usually to include another php script. In this case imagine that example.php contains a string value assigned to $xmlstr.

$movies->addAttribute('value','your value here'); $action->addAttribute('value','your value here'); $user->addAttribute('id','your value here'); 

Spent three hours to combine SimpleXML with other solutions and finally get this. It works and I hope it will be useful.

$xml_data = new SimpleXMLElement(' '); $arrXml = [ "categories" => [ 'category' => [ '@attributes' => [ 'id' => '123', 'parent_id' => '12345' ], '@value' => 'Bikes' ] ], "properties" => [ 'property' => [ 'id' => '123', 'categoryId' => '1', 'name' => 'Color', 'values' => [ 'value' => [ "id" => '1', "name" => 'Black' ], 'value' => [ "id" => '2', "name" => 'White' ] ] ] ], "products" => [ 'products' => [ 'id' => '1231231', 'categoryId' => '123', 'model' => [ '@attributes' => [ 'foo' => 'bar', ], '@value' => 'Avalanche' ], 'article' => '1.0 2011', 'vendor' => 'GT', ] ] ]; array_to_xml($arrXml,$xml_data); //saving generated xml file; $result = $xml_data->asXML('test.xml'); 
  Bikes   123 1 Color  2 White      1231231 123 Avalanche 
1.0 2011
GT
function array_to_xml( $data, &$xml_data ) < foreach( $data as $key =>$value ) < if (!empty($value)) < if( is_array($value)) < if (!empty($value["@attributes"])) < $subnode = $xml_data->addChild($key, $value["@value"]); foreach ($value["@attributes"] as $key1 => $val1) < $subnode->addAttribute($key1, $val1); > > else if ($key == "@value") < foreach ($value as $attr =>$attrVal) < $subnode = $xml_data->addChild("$attr", $attrVal); array_to_xml($attrVal, $subnode); > > else < if (!empty($value)) < $subnode = $xml_data->addChild($key); array_to_xml($value, $subnode); > > > else < $xml_data->addChild("$key",$value); > > > > 

Источник

PHP addAttribute() Function

Add an attribute to the root element () and to the element:

$xml = new SimpleXMLElement($note);
// Add attribute to root element
$xml->addAttribute(«type»,»private»);
// Add attribute to body element
$xml->body->addAttribute(«date»,»2014-01-01″);

Definition and Usage

The addAttribute() function appends an attribute to the SimpleXML element.

Syntax

Parameter Values

Parameter Description
name Required. Specifies the name of the attribute to add
value Optional. Specifies the value of the attribute
ns Optional. Specifies a namespace for the attribute

Technical Details

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью