Whats the easiest way to take a JSON or Array object and convert it to XML. Maybe I am looking in all the wrong places but I am not finding a decent answer to get me on track with doing it. Is this something I would have to somehow build myself? Or is there something like json_encode/json_decode that will take an array or json object and ust pop it out as a xml object?
Here is my variant of JSON to XML conversion.
I get an array from JSON using json_decode() function:
$array = json_decode ($someJsonString, true);
Then I convert the array to XML with my arrayToXml() function:
$xml = new SimpleXMLElement('<root/>');
$this->arrayToXml($array, $xml);
Here is my arrayToXml() function:
/**
* Convert an array to XML
* #param array $array
* #param SimpleXMLElement $xml
*/
function arrayToXml($array, &$xml){
foreach ($array as $key => $value) {
if(is_int($key)){
$key = "e";
}
if(is_array($value)){
$label = $xml->addChild($key);
$this->arrayToXml($value, $label);
}
else {
$xml->addChild($key, $value);
}
}
}
Check it here: How to convert array to SimpleXML
and this documentation should help you too
Regarding Json to Array, you can use json_decode to do the same!
I am not sure about the easiest way. Both are relatively simple enough as I see it.
Here's a topic covering array to xml - How to convert array to SimpleXML and many pages covering json to xml can be found on google so I assume it's pretty much a matter of taste.
Related
Those data in $data variable. When I'm using dd($data); I got this:
CurlHandle {#1918 ▼
+url: "https://example.com"
+content_type: "application/json; charset=UTF-8"
+http_code: 200
+header_size: 887
+namelookup_time_us: 139522
+pretransfer_time_us: 326662
+redirect_time_us: 0
+starttransfer_time_us: 668686
+total_time_us: 668752
}
I want to convert this data to an array.
I'm using this: $arr = json_decode($data,true);
But, this is not working. Now, how can I convert this?
You can use below solution
$yourArray = json_decode(json_encode($yourObject), true);
and this convert object to an array for more info
Objects are, in PHP, maybe iterable. Notice, you may iterate through an object's public fields only via the foreach loop. So the following works:
$array = [];
foreach ($object as $property) {
$array[] = $property; // Stores public field only
}
var_dump($array);
Simply to get an array of object properties, you may use the get_object_vars() function.
var_dump(get_object_vars($object));
You may cast an object to be an array as #MoussabKbeisy said. And this would be the easiest way:
$array = (array) $object;
Here is another way is using ArrayIterator:
$iterator = new ArrayIterator($object);
var_dump(iterator_to_array($iterator));
while this is a PHP Object so you can deal with it by 2 ways:
1- if you want to get on of it's parameters, you can simply use
$yourObject->parameter;
2- if you need to use convert and use it as array, then there is different ways to convert an object to an array in PHP
//1
$array = (array) $yourObject;
//2
$array = json_decode(json_encode($yourObject), true);
Also see this in-depth blog post:
Fast PHP Object to Array conversion
I currently have this large JSON file: hastebin
But just want the titles of the posts.
I've tried this...
$json = $page;
$o = json_decode($json, true);
echo($json);
$titles = $o["*"]["*"]["*"]["*"]["title"];
var_dump($titles);
But it isn't working - it's returning NULL! Sometimes it just doesn't return anything.
If anyone is wondering, yes this is from Reddit.
This should do it:
$titles = array_map(function($post) {
return $post['data']['title'];
}, $o['data']['children']);
I'm not sure what you expected using "x" indices, but you should probably read about arrays.
PHP can't use wildcards like * in array keys. Whatever string you use to reference the key, it's going to try to find a key with that exact string. So what you tried can't work because there aren't any * keys.
You can get it by iterating all the levels, or iterating the outer level and referring to the proper nested key. But if you're just looking for all instances of 'title' a recursive method may be an easier way to get them.
array_walk_recursive($o, function($value, $key) use (&$titles) {
if ($key == 'title') $result[] = $value;
});
var_dump($titles);
This will get any value of 'title' regardless of its depth in the array, so if that's not what you want, then you'll need to iterate it and specifically reference the proper ones.
It's very hard to deal directly with such a long JSON document. The returned result from the page is not a valid JSON. It contains some HTML tags, but if you take the posts data and insert it in a file you can do the following according to the structure of your JSON (You can find your JSON in an external link here):
<?php
header("Content-Type:application/json");
$posts=file_get_contents('json.php');
//decode your JSON STRING
$posts=json_decode($posts,true);
//create a title variable to store your titles
$titles=array();
foreach($posts['data']['children'] as $child)
{
array_push($titles,$child['data']['title']);
}
echo json_encode($titles);
?>
You can even use this approach using a URL but ensure that it will return a valid JSON with no html
I have some issue with a decoded Json object sended to a php file. I have tried some different format like this
{"2":"{Costo=13, ID=9, Durata_m=25, Descrizione=Servizio 9}","1":"{Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}"}
or this.
[{"Costo":"7.5","ID":"3","Durata_m":"30","Descrizione":"Barba Rasoio"},{"Costo":"4.5","ID":"4","Durata_m":"20","Descrizione":"Barba Macchinetta"}]
In order the first, any suggestions helps me, then i have converted previous string using GSON, however php doesn't decode.
This is my php:
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data['servizi'] as $key => $value)
{ echo "Key: $key; Value: $value<br />\n";
}
How can I access single elements of array? What I'm doing wrong? Thanks in advance
I think you should check the content in this way
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) {
echo "FROM PHP: " . $value;
echo "Test : " .$value['ID'];
}
your elements of {Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}
are not properly formated as an array element. That is a pure string and not an array value.
This is a json object with 1 element of array:
{
"1": {
"Costo": 7,
"ID": 8,
"Durata_m": 20
}
}
The Inside are json objects. Therefore your json string was not properly formated to operate with that logic. What you had was an element of a string. That is the reason why it was a valid json (passing jsonlint) but was not the correct one that you wanted to use.
UPDATE
Because this format is fix, I have a non-elegant way:
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) {
//to separate each element
$newArray = explode(',',$value);
$newItem = explode('=', $newArray[1]);
echo "ID". $newItem[1];
}
That would be the dirty way to do it ONLY IF THE PLACEMENT OF DATA IS FIX. (ie the second element of the first explode is always ID.
I will leave it to someone else to make the suggested code better. I would recommend more to ensure that the json you are receive is proper because as I explained, it is incorrectly formated and as an api developer, you want an adaptive way for any given client to use the data efficiently.
I am using a loop to populate an array called $list. it is working like a charm..
// $content is a DOMNodeList Object
// $value is a DOMElement Object
$list = array();
foreach ($content as $value){
array_push($list, 'title'=>$value->nodeValue);
}
Eventhough my loop is populating my array correctly, I would like to digg into that DOM thing a little more to understand things better (this DOM thing is to new to me...). So what I would like, is to see how the DOMNodeList Object ($content) and DOMElement Object ($value) looks like.
So my question is simple: how can I "echo-out" those 'elements'?
Better than "echo-out" DomElement, read the documentation: http://php.net/manual/en/class.domelement.php.
If you want to see XML representation, use http://www.php.net/manual/en/domnode.c14n.php,
i.e.
echo $value->c14N(false,true);
I have a multi-dimensional multi-object array from a simplexml_import_dom() function call.
A slice of one section of the array:
[Price] => SimpleXMLElement Object
(
[Prices] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[MType] => A
[PType] => R
This is causing me quite a bit of problems when trying to read nested objects. I have tried to loop through the array using multiple get_object_vars() but because the depth and location of the nested objects is continually changing I haven't been able to yield desirable results.
Does PHP contain a function that I haven't been able to find to convert a multi-dimensional multi-object array to a standard multi-dimensional array? Or has anyone solved this problem before?
Thanks for your help!
The question is often asked, but there's a fundamental issue that has to be addressed on a case-by-case basis when converting a XML tree to an array, which makes an one-size-fits-all method impossible: how do you differentiate nodes from attributes?
For instance, how would you convert this XML to an array:
<node val="attr"><val>child</val></node>
Also, a node can have any number of children with the same name, which you can't emulate with an associative array.
Long story short, you'll have to cook up your own solution. Judging from your output, it would look something like this:
$arr = array();
foreach ($Price->Prices as $Prices)
{
$tmp = array();
foreach ($Prices->attributes() as $k => $v)
{
$tmp[$k] = (string) $v;
}
$arr[] = $tmp;
}
If it's not what you're looking for, please edit your question and add an example of the source document (XML) as well as the expected result (the array.)
Are you aware that these objects have functions that you can use? Try the following:
foreach ($simpleXmlObject->children() as $element) {
echo $element->getName();
}