PHP, SimpleXML arrays. Unanticipated casting of an array to a string - php

Sample XML:
<root>
<ratings>3</ratings>
<ratings>5</ratings>
<ratings>7</ratings>
</root>
The following code is the basis for my small application, it works as would be expected:
<?php
// $xml is some simplexml object
sizeof($xml->ratings); //3
foreach($xml->ratings as $rating){
echo($rating->value."::"); //this echoes all 3 rating values: 3::5::7
}
?>
This next code, which I would normally consider to be equivalent is not. And I have no idea why:
<?php
// $xml is some simplexml object
$ratings = $xml->ratings;
sizeof($ratings); //3, all is well so far
foreach($ratings as $rating){
echo($rating."::");
/*this echoes a never-ending list of ratings,
looking like 3::5::5::5::5::5::5::5...... */
}
?>
My feeling is that the assignment operator is casting the array of simplexml objects (ratings objects) as something odd, but have no clue as to how.
Other little hints:
var_dump($xml);
/* Output is:
object(SimpleXMLElement)#7 (1) {
["ratings"]=>
array(3) {
[0]=>
string(1) "3"
[1]=>
string(1) "5"
[2]=>
string(1) "7"
}
}
*/
var_dump($ratings);
/* Output is:
object(SimpleXMLElement)#6 (1) {
[0]=>
string(1) "3"
}
*/

Your echos are not the same:
echo($rating."::");
should be
echo($rating->value."::");

Ok, cleaning up some of my own work. After attempting to simplify my issue more, I was not able to prove it. After messing with the actual code, I assume this means I have some sort of mutating object elsewhere in my app that is going bonkers and creating weird results in this xml parsing. Sorry for the confusion and needless question (I guess this proves why i'm trying to refactor some of my complexity out of this app).
As a parting gift, here is the test-suite of code that I used (from simple to more realistic) that I used to prove that all worked as advertised:
<?php
$string = <<<XML
<?xml version='1.0'?>
<root>
<ratings>3</ratings>
<ratings>5</ratings>
<ratings>7</ratings>
</root>
XML;
$xml = simplexml_load_string($string);
var_dump($xml);
echo("Size:".sizeof($xml->ratings)."\n");
foreach($xml->ratings as $rating){
echo($rating."::");
}
echo("\n"."------"."\n");
$ratings = $xml->ratings;
echo("Size:".sizeof($ratings)."\n");
foreach($ratings as $rating){
echo($rating."::");
}
echo("\n\n\n\n"."||||New Example||||"."\n\n\n\n");
$stringthree = <<<XML
<root attr1="val" attr2="desc">
<field-one>val</field-one>
<elm-two attr-name="foo">elmTwoVal1</elm-two>
<elm-three>elmThreeVal1</elm-three>
<elm-two attr-name="bar">elmTwoVal2</elm-two>
<elm-three>elmThreeVa2</elm-three>
<elm-two attr-name="bear">elmTwoVal3</elm-two>
<elm-three>elmThreeVal3</elm-three>
</root>
XML;
$xmlthree = simplexml_load_string($stringthree);
var_dump($xmlthree);
echo("Size:".sizeof($xmlthree->{'elm-two'})."\n");
foreach($xmlthree->{'elm-two'} as $elm){
echo($elm."::");
}
echo("\n"."------"."\n");
$elmMain = $xmlthree->{'elm-two'};
echo("Size:".sizeof($elmMain)."\n");
foreach($elmMain as $elm){
echo($elm."::");
}
?>

Related

How to convert XML with multiple prefixes to object

We have xml similiar to this:
<?xml version="1.0" encoding="UTF-8"?>
<animal:race>
<animal:dog>
<specification:color>Black</specification>
</animal:dog>
<animal:cat>
<animal:name>Flappie</animal:name>
</animal:cat>
</animal:race>
We tried simplexml_load_file("file.xml",null,null,"animal");
which returns
object(animal:race)#1 (2) {
["dog"]=> object(SimpleXMLElement)#2 (0) {
}
["cat"]=> object(SimpleXMLElement)#2 (1) {
[animal:name] => string "flappie"
}
}
We've seen multiple posts about this but can't seem to get any of this working stripping the prefixes away is not an option cause we need those in a later stage...
Can someone perhaps make a bit of code which converts this to an valid object so that we can adjust it to our own xml.

Reading XML file with namespaces

I need som help reading a XML that has namespaces.
I can read file with out any namepaces but not with namespaces..
XML sample:
<?xml version="1.0" encoding="utf-8"?>
<OrderResponse xmlns:cac="urn:basic:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:xsi="http://www.w3.org/" xmlns:cbc="urn:basic:names:specification:ubl:schema:xsd:BasicComponents-2" xmlns="urn:basic:names:specification:ubl:schema:xsd:OrderResponse-2">
<cbc:UBLVersionID>2.1</cbc:UBLVersionID>
<cbc:AccountingCostCode>TESTER TEST</cbc:AccountingCostCode>
<cac:OrderReference>
<cbc:ID>100067010</cbc:ID>
<cbc:IssueDate>2016-06-15</cbc:IssueDate>
<cbc:OrderTypeCode>EDI</cbc:OrderTypeCode>
</cac:OrderReference>
</OrderResponse>
I need to get the value of the ..
Im trying do it with DomDocument.
Here is my code:
function SearchXMLID($xml){
var_dump($xml);
$doc = new DOMDocument();
$doc->load($xml);
$id = $doc->getElementsByTagNameNS('urn:basic:names:specification:ubl:schema:xsd:CommonAggregateComponents-2','cbc:ID');
foreach($id as $i){
echo "<pre>";var_dump('NS',$i->nodeValue,PHP_EOL);"</pre>";
}
}
$files = glob('dataXMl/*xml');
echo "<pre>";var_dump($files,PHP_EOL);"</pre>";
foreach($files as $f){
SearchXMLID($f);
}
This code works but is getting all namespaces with 'cbc:' and stores the in a string..
array(1) {
[0]=>
string(17) "dataXMl/test1.xml"
}
string(1) "
"
string(17) "dataXMl/test1.xml"
string(2) "NS"
string(40) "
100000050
2016-06-15
EDI
"
string(1) "
"
It gets all tags with the namespace 'cbc'.. but i want to get the tag 'cbc:ID' only.
What am i doing wrong?
I'm no expert with php coding but my gut tells me that both of your parameters for getElementsByTagNameNS are wrong.
Try this:
$id = $doc->getElementsByTagNameNS('urn:basic:names:specification:ubl:schema:xsd:BasicComponents-2','ID');
i.e. use the correct namespace-uri: "urn:basic:names:specification:ubl:schema:xsd:BasicComponents-2"
and drop the cbc prefix

var_dump for DOMNodeList printout unexpected result

I have a xml file I load it as the following:
//$file the file system path of the xml file
function getTopicsList($file){
$doc = new DOMDocument();
$doc->load( $file );
var_dump($doc->getElementsByTagName('topic'));
return $doc->getElementsByTagName('topic');
}
The loaded xml file contents is something like the following:
<?xml version="1.0" encoding="UTF-8"?>
<topics>
<topic>
<title>Title1</title>
<keywords>"Some Keys"</keywords>
</topic>
<topic>
<title>The Title</title>
<keywords>Another Key</keywords>
</topic>
<topic>
<title>A Title</title>
<keywords>Key two</keywords>
</topic>
</topics>
The var_dump() in the above code just printout limited information such as:
object(DOMNodeList)#30 (1) {
["length"]=>
int(3)
}
I expected that it should print at least the properties of that object i.e the xml tags and its values. I tried to use other functions such as print_r() and var_export() but there is no details I want.
No, this is node list. You can iterate it with foreach or access nodes using the item() method.
Node lists are used at different places, getElementsByTagName() is one, another is the $childNodes property. Xpath expressions return node lists, too.
Be aware that the nodes can be not only elements but several node types. Like text, cdata section or attribute.
You can use var_dump() to dump a single node. This works with PHP >= 5.3.11 or >= 5.4.1.
$dom = new DOMDocument();
$dom->loadXML('<foo/>');
var_dump($dom->documentElement);
Output:
object(DOMElement)#2 (18) {
["schemaTypeInfo"]=>
NULL
["tagName"]=>
string(3) "foo"
["textContent"]=>
string(0) ""
["baseURI"]=>
string(1) "/"
["localName"]=>
string(3) "foo"
["prefix"]=>
string(0) ""
["ownerDocument"]=>
...

PHP SimpleXMLElement XPath Selection

I have the following XML: http://pastebin.com/QiRK72BK
which is generated in response to a REST query. My code is very simple:
$xml = simplexml_load_file($url);
var_dump($xml->getName());
var_dump($xml->xpath("serverDetail/apiEnv"));
in an attempted test case. The first var_dump reveals that the XML file is indeed being loaded:
string(21) "GeneralSearchResponse"
However, the second var_dump puzzles me. I feel it should definitely match some data, but instead I get
array(0) { }
I've also tried the xpath "/serverDetail/apiEnv" "//apiEnv" and "/" and always get an empty array. Am I misunderstanding xpath or perhaps missing some initialization step?
Your XML is using a namespace:
$xml->registerXPathNamespace('u', 'urn:types.partner.api.shopping.com');
var_dump($xml->xpath("//u:serverDetail/u:apiEnv"));
Output:
array(1) {
[0]=>
object(SimpleXMLElement)#2 (1) {
[0]=>
string(7) "sandbox"
}
}
Edit: Dirty workaround, might be helpful though:
$xml = simplexml_load_file($url);
$xmlStr = str_replace("xmlns", "ns", $xml->asXML());
$xml = new SimpleXMLElement($xmlStr);
var_dump($xml->xpath("serverDetail/apiEnv"));

PHP xpath result as array of strings

I have seen several similar questions, but not found the exact answer I'm looking for. It may be that the functionality I am looking for does not exist.
If I do an xpath query that results in an array of objects, but each object only holds one value, a string, I'd like to quickly convert that into an array of strings. Obviously I can do a foreach on the object and push the string value onto a new array, but if there is a built in function I'm not thinking of, please let me know.
example:
array(3) {
[0]=>
object(SimpleXMLElement)#24 (1) {
[0]=>
string(20) "Network Media Player"
}
[1]=>
object(SimpleXMLElement)#25 (1) {
[0]=>
string(12) "Music Player"
}
[2]=>
object(SimpleXMLElement)#26 (1) {
[0]=>
string(8) "Juke Box"
}
}
I'd like that to become
array('Network Media Player','Music Player','Juke Box')
Here's my test :
<pre><?php
$xml = "<data>
<item>
<value>Network Media Player</value>
</item>
<item>
<value>Music Player</value>
</item>
<item>
<value>Jukebox Player</value>
</item>
</data>";
$sx = simplexml_load_string($xml);
print_r($sx);
print_r(explode("|",implode("|",$sx->xpath("//data/item/value"))));
?></pre>
and here's the result : http://codepad.org/ZkaWpzMc

Categories