Monday, September 3, 2018

xml - Displaying data via PHP and SimpleXML problem




I have gone through a lot of the SimpleXML questions on this site. My data is a bit strange and I cannot change that. I am trying to get things like 'Building1' and 'Hostname1' from my data, so I can take that data and look up other data, then display it.



Here is a sample of my data:



    



Hostname 1



Windows 7


Building 1





Hostname 2


Windows 10


Building 2


........



And here is how I am trying to look at it:



$xml = simplexml_load_file(data.xml);
print_r($xml);
$testArray = new SimpleXMLElement($xml);
$records = $testArray->results->result;
print_r($records);



For some reason I just cannot figure out how to get the data from the xml elements. If anyone can point me in the right direction, I'd appreciate it. I've tried many, many options. Thanks-


Answer



This is a really common mistake, but a really hard one to spot if you don't know what you're looking for: the first object you get back when parsing with XML is the root element, not something representing the document.



So in your case, $testArray is the element , and you want $testArray->result not $testArray->results->result.



By the way, "testArray" is a bad name for this variable - it's not an array, it's an object.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...