PHP SimpleXML parse differently depending on line break - php

I want to parse XML string using SimpleXML on PHP.
$xml = '<root><case1><name> </name></case1><case2><name></name></case2><case3><name>ukits</name></case3></root>';
libxml_use_internal_errors(true);
$content = simplexml_load_string($xml);
if ($content === false) {
libxml_clear_errors();
}
print_r($content);
$content = objectToArray($content);
print_r($content);
function objectToArray($obj) {
if (is_object($obj)) { $obj = (array) $obj; }
if (count($obj) == 0) { $obj = ''; }
if (is_array($obj)) {
$new = array();
foreach ($obj as $key => $val) {
$new[$key] = objectToArray($val);
}
} else {
$new = $obj;
}
return $new;
}
This code returns:
SimpleXMLElement Object
(
[case1] => SimpleXMLElement Object
(
[name] => SimpleXMLElement Object
(
[0] =>
)
)
[case2] => SimpleXMLElement Object
(
[0] => SimpleXMLElement Object
(
)
)
[case3] => SimpleXMLElement Object
(
[name] => ukits
)
)
Array
(
[case1] => Array
(
[name] => Array
(
[0] =>
)
)
[case2] => Array
(
[0] =>
)
[case3] => Array
(
[name] => ukits
)
)
There seems to be 2 unexpected problems. In case1, name tag has a OBJECT child (not spaced string). In case2, case2 tag has a numeric array.
But, if the XML string contains line break or space after 'name' tag, the result is different. like this:
$xml = '<root><case1><name> </name>
</case1><case2><name></name>
</case2><case3><name>ukits</name></case3></root>';
The same code returns:
SimpleXMLElement Object
(
[case1] => SimpleXMLElement Object
(
[name] => SimpleXMLElement Object
(
)
)
[case2] => SimpleXMLElement Object
(
[name] => SimpleXMLElement Object
(
)
)
[case3] => SimpleXMLElement Object
(
[name] => ukits
)
)
Array
(
[case1] => Array
(
[name] =>
)
[case2] => Array
(
[name] =>
)
[case3] => Array
(
[name] => ukits
)
)
This result is that I want to get.
The point is WHY the results of "same structured XML strings" are differnt depend on line break.
And how do I do If I want to get what I want like second result?
(An input string have to contain no line break.)
Here is my configuration:
CentOS 6.7
PHP 5.4.45
SimpleXML Revision $Id: 16070fc92ad6f69cebb2d52ad3f02794f833ce39 $
libxml2 Version 2.7.6

Related

From XPath result to simple array. How i can to do it without use foreach (or scan array)

Using this query:
$xml->xpath( "/root/label//#name" );
I get this array:
Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => Pippo
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => Caio
)
)
[2] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => Sempronio
)
)
How i can have array with this output:
Array
(
[0] => Pippo
[1] => Caio
[2] => Sempronio
)
Thanks.
You could simply cast every element to string through array_map:
$elements = $xml->xpath('/root/label//#name');
$names = array_map(fn(SimpleXMLElement $element) => (string) $element, $elements);
Or, with PHP < 7.4:
$elements = $xml->xpath('/root/label//#name');
$names = array_map(function (SimpleXMLElement $element) {
return (string) $element;
}, $elements);
Demo
Note that array_map does loop over every element in the background.

Merge arrays in an object

Im new to php and json. can you please suggest me on how to get the my desired output.
JSON File:
{
"1415772360":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"12"},
{"peaches":"2"},
{"banana":"1"}
],
"1415772420":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"7"},
{"peaches":"1"},
{"banana":"1"}
]
}
Desired Output
[
{
"minute":"1415772360",
"apple":"0",
"mango":"0",
"grapefruit":"0",
"melons":"12",
"peaches":"2",
"banana":"1”
},
{
"minute":"1415772420",
"apple:"0",
"mango":"0",
"grapefruit":"0",
"melons":"7",
"peaches":"1",
"banana":"1”
}
]
How can I do this in PHP?
I really appreciate your help. Thanks.
I would give json_decode a try. It won't get your desired output, but it will create an array from your JSON.
Documentation: http://php.net/manual/en/function.json-decode.php
My test:
$json = "{\"1415772360\":[{\"apple\":\"0\"},{\"mango\":\"0\"},{\"grapefruit\":\"0\"},
{\"melons\":\"12\"},{\"peaches\":\"2\"},{\"banana\":\"1\"}], \"1415772420\":
[{\"apple\":\"0\"},{\"mango\":\"0\"},{\"grapefruit\":\"0\"},{\"melons\":\"7\"},
{\"peaches\":\"1\"},{\"banana\":\"1\"}]}";
$new = json_decode($json);
print_r($new);
Output:
stdClass Object ( [1415772360] => Array ( [0] => stdClass Object ( [apple] => 0 )
[1] => stdClass Object ( [mango] => 0 ) [2] => stdClass Object ( [grapefruit] => 0 )
[3] => stdClass Object ( [melons] => 12 ) [4] => stdClass Object ( [peaches] => 2 )
[5] => stdClass Object ( [banana] => 1 ) ) [1415772420] => Array ( [0] => stdClass Object ( [apple] => 0 )
[1] => stdClass Object ( [mango] => 0 ) [2] => stdClass Object ( [grapefruit] => 0 )
[3] => stdClass Object ( [melons] => 7 ) [4] => stdClass Object ( [peaches] => 1 )
[5] => stdClass Object ( [banana] => 1 ) ) )
tyteen4a03 is correct that this just requires some looping to re-write the structure. This would be done as follows:
// Original JSON string
$json = '{
"1415772360":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"12"},
{"peaches":"2"},
{"banana":"1"}
],
"1415772420":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"7"},
{"peaches":"1"},
{"banana":"1"}
]
}';
// Convert JSON to array
$content = json_decode($json);
// Create new array container
$crate = array();
// Get minutes
foreach ($content AS $minute => $fruitbasket) {
$tmp = new stdClass;
$tmp->minutes = $minute;
// Get array of objects
foreach ($fruitbasket AS $fruits)
{
// Get object element and value
foreach ($fruits AS $key => $value)
{
// add to temporary object
$tmp->$key = $value;
}
}
// write to new array
$crate[] = $tmp;
}
print(json_encode($crate));

How to retrieve value from SimpleXMLElement Object

After calling the prestashop webservice, I recieved the response as shown below:
SimpleXMLElement Object
(
[order] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => 1
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => 2
)
)
)
)
I tried to retrive the content by looping as shown below:
foreach($resources as $resource){
echo '<pre>';
print_r($resource['id']);
echo '</pre>';
}
This gives me:
SimpleXMLElement Object
(
[0] => 1
)
SimpleXMLElement Object
(
[0] => 2
)
How can I retrieve 1 and 2 which are the values of these objects? thanks
I hate simplexml...
<?php
$xml = file_get_contents('xml.xml');
$xml = new SimpleXMLElement($xml);
foreach($xml as $key => $value)
{
$attrs = $value->attributes();
foreach($attrs as $attr_k => $attr_v)
echo $attr_k.": ".$attr_v."\n";
}

Parsing PHP SimpleXMLElement

I am using php to consume a web service (in coldfusion) to validate against the active directory. My code is below.
<?php
$racf = $_SERVER['AUTH_USER'];
//echo $racf;
//echo $myracf = trim($racf, "FEDERATED\.");
//get authenticated user
$arrUser = explode("\\", $_SERVER["LOGON_USER"]);
$racf = $arrUser[1];
echo $racf.'<br ><br >';
$logins = "http://acoldfusionwebservice/login.cfc?method=loginad&racf=$racf";
if( ! $xml = simplexml_load_file($logins) )
{
echo 'unable to load XML file';
}
else
{
//echo 'XML file loaded successfully <br />';
print_r ($xml);
}
?>
And this produces the following.
SimpleXMLElement Object
(
[#attributes] => Array
(
[version] => 1.0
)
[header] => SimpleXMLElement Object
(
)
[data] => SimpleXMLElement Object
(
[recordset] => SimpleXMLElement Object
(
[#attributes] => Array
(
[rowCount] => 1
[fieldNames] => cn,mail,givenName,sn
)
[field] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => cn
)
[string] => B000000
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => mail
)
[string] => john.doe#company.com
)
[2] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => givenName
)
[string] => John
)
[3] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => sn
)
[string] => Doe
)
)
)
)
)
Can someone help me to parse this information so that I can assign variables and use them. Thanks.
Try
$xml->data->recordset->field[0]->string
I think that field[0] is an Object again

Read SimpleXmlElement object

I have the following xml to be parsed.
Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[rel] => http://schemas.google.com/g/2005#other
[address] => xyz#gmail.com
[primary] => true
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[rel] => http://schemas.google.com/g/2005#other
[address] => abc#gmail.com
[primary] => true
)
)
)
I have this above xml and I need to get only adress from this xml.
foreach ($result as $title) {
$email[$count++]=$title->attributes()->address->__toString;
}
debug($email);
The result is this. But I want only address . need some help.
Array
(
[0] => SimpleXMLElement Object
(
)
[1] => SimpleXMLElement Object
(
)
)
see : http://www.php.net/manual/en/simplexmlelement.attributes.php
Return Values
Returns a SimpleXMLElement object that can be iterated over to loop through the attributes on the tag.
the solution is to cast the value into string,
for example :
$email[$count++]=(string)$title->attributes()->address;
Or iterate the return value will work as well
eg:
foreach($title->attributes() as $key => $val)
{
if ($key == 'address') $email[$count++] = $val;
}

Categories