Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php parse simple xml attributes

Tags:

php

xml

simplexml

I'm having some trouble with an xml file, I have found all sorts of examples/guides around the web and on this site but I can't seem to see one like this:

I have an XML file like so:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<items item1="1" item2="2" item3="3" item4="4"/>
<items item1="1" item2="2" item3="3" item4="4"/>
<items item1="1" item2="2" item3="3" item4="4"/>
</root>

I've not seen the data set out like this before and when I try:

<?php

$obj = simplexml_load_string("sample.xml");
print_r($obj);
?>

I get the error:

Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 1: parser error : Start tag expected, '<' not found

I have run the xml file through the check at www.xmlvalidation.com and all comes back ok, am I missing something?

I am looking to be able to echo the value of the item attributes in a while loop.

like image 826
Joe Avatar asked Sep 10 '26 18:09

Joe


1 Answers

You're attempting to load XML from a file with simplexml_load_string(), which expects a string input. Instead, use simplexml_load_file().

$obj = simplexml_load_file("sample.xml");
like image 120
Michael Berkowski Avatar answered Sep 13 '26 07:09

Michael Berkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!