PHP Object as Xml Document

PHP Object as XML Document

take a look at PEAR's XML_Serializer package. I've used it with pretty good results. You can feed it arrays, objects etc and it will turn them into XML. It also has a bunch of options like picking the name of the root node etc.

Should do the trick

PHP: How do I write XML object into a XML file

simplexml_load_file returns a SimpleXMLElement object. If you look through the documentation you will find this:

public mixed asXML ([ string $filename ] )

In other words:

$file = "country_request.xml";
$xml = simplexml_load_file($file);

// Do you stuff here...

if ($xml->asXML($file)) {
echo 'Saved!';
} else {
echo 'Unable to save to file :(';
}

Class to turn PHP objects into XML

Multiple levels require a recursive kind of processing - as you don't know the number of levels upfront. While doing the recursion you also need to take care which XML Elements are opened and such.

What you do is that you serialize a PHP object into XML. You're not the first one who needs this, PHP ships with a XML serializer that follows the WDDX specification, for example with the wddx_serialize_value function:

$object = (object) array('hello' => (object) array('value' => 'world') );

echo wddx_serialize_value($object);

Which will give this XML (Demo):

<wddxPacket version='1.0'>
<header/>
<data>
<struct>
<var name='php_class_name'>
<string>stdClass</string>
</var>
<var name='hello'>
<struct>
<var name='php_class_name'>
<string>stdClass</string>
</var>
<var name='value'>
<string>world</string>
</var>
</struct>
</var>
</struct>
</data>
</wddxPacket>

If you need a different output, you need to write the serialization on your own. Within symfony2 (Symfony2 Serializer Component) and Pear (XML_Serializer) you find existing PHP code that does serialization with XML output.

How can I convert a PHP stdCLass object to XML?

Don't try to build a generic convert. It is a lot easier just to read a specific object structure and create a DOM from it. This allows you to define the structure, validate and reformat the values, ignore unneeded values, ...

$data = getData();

$document = new DOMDocument();
// create and append a document element
$document->appendChild(
$stock = $document->createElement('stock')
);

// iterate data array
foreach ($data->EtatStock as $stockData) {
// create and append an element for each item
$stock->appendChild(
$item = $document->createElement('item')
);
// add a child element with text content
$item
->appendChild($document->createElement('CodeMag'))
->textContent = $stockData->CodeMag;
$item
->appendChild($document->createElement('LibMag'))
->textContent = $stockData->LibMag;
// add value as an attribute
$item->setAttribute('quantity', $stockData->QteStock);
}

$document->formatOutput = true;
echo $document->saveXML();

function getData() {
$json = <<<'JSON'
{
"EtatStock": [
{
"CodeMag": "001",
"LibMag": "SO SHOCKING",
"QteStock": 2000
}
]
}
JSON;
return json_decode($json);
}

Output:

<?xml version="1.0"?>
<stock>
<item quantity="2000">
<CodeMag>001</CodeMag>
<LibMag>SO SHOCKING</LibMag>
</item>
</stock>

Using SimpleXML to create an XML object from scratch

Sure you can. Eg.

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
<content type="latest"/>
</news>

Have fun.

Convert SimpleXMLElement object to XML format in php

Try Somthing like this..

 $doc = new DOMDocument();
$doc->formatOutput = TRUE;
$doc->loadXML($sxml->asXML());
$xml = $doc->saveXML();

For more information check this link

http://us2.php.net/manual/en/simplexmlelement.asxml.php

Create XML Document with PHP in an easy way

The first thing that comes to mind is that you have got code-repetition. You perhaps want to reduce that. This can be done by moving duplicate code into a function of it's own.

To do that fast, PHP has closures. Let's line that up:

You have a collection of vehicles and each vehicle just has properties and values. So you add a property to a vehicle. BTW, createElement does take a text already as value, so that you don't need to create the text-nodes. So let's wrap the duplicate code into functions and then just call these functions to create the XML. That already - through parametrization - shows your structure. Just differ between the definitions of the functions (first part) and the apply of those (second part):

<?php
/**
* Create XML Document with PHP in an easy way
*
* @link http://stackoverflow.com/q/19702911/367456
*/

/**
* @param DOMNode $node
* @return DOMDocument
*/
$doc = function (DOMNode $node = NULL) {
return $node ? ($node->ownerDocument ? : $node) : new DOMDocument();
};

/**
* @param DOMElement $element
* @param string $property
* @param string $text
* @return DOMElement the element the proeprty was added to
*/
$prop = function (DOMElement $element, $property, $text) {
return $element->appendChild(
$element->ownerDocument->createElement($property, $text)
);
};

/**
* @param DOMNode $element
* @param string $name
* @return DOMElement
*/
$element = function (DOMNode $element, $name) use ($doc) {
return $element->appendChild(
$doc($element)->createElement($name)
);
};

So after all those functions have been defined, on to the second part:

$prop(
$vehicle = $element(
$vehicles = $element(
$doc()
, 'Vehicles'
)
, 'Vehicle'
)
, "Number"
, "AW2CM31Y8"
);

$prop(
$vehicle
, "Year"
, "2013"
);

$prop(
$vehicle
, "Make"
, "VOLKSWAGEN"
);

$prop(
$vehicle
, "Model"
, "NEW BEETLE"
);

$prop(
$vehicle
, "Color"
, "Black"
);

Et voila. This has revealed some structure. Code-duplication has been removed as well. The only thing left is to finally echo the result out:

header("Content-type: text/xml");
echo $doc($vehicles)->saveXML();

If you look at the code you can even read that it literally does reverse the data-structure to create the XML. So next thing would be to make use of some kind of traversal, but that needs the definition of a data-structure first, not only the definition of the code-structure as it has been done so far (and which should already be of use for you).

Online Example: https://eval.in/59090



Related Topics



Leave a reply



Submit