I currently have the following code :
$content = "
<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>";
I need to find a method to create and array as name=>value
. E.g Manufacturer => John Deere
.
Can anyone help me with a simple code snipped I tried some regex but doesn't even work to extract the names or values, e.g.:
$pattern = "/<name>Manufacturer<\/name><value>(.*)<\/value>/";
preg_match_all($pattern, $content, $matches);
$st_selval = $matches[1][0];
First of all, never use regex to parse xml...
You could do this with an XPATH query...
First, wrap the content in a root tag to make the parser happy (if it doesn't already have it):
Then, load the document
Then, initialize the XPATH
Write your query:
Then, execute it:
If I did the xpath right, it
$manufacturer
should beJohn Deere
...You can see the docs on DomXpath, a basic primer on XPath, and a bunch of XPath examples...
Edit: That won't work (PHP doesn't support that syntax (following-sibling). You could do this instead of the xpath query:
Using
XMLReader
:The output is:
You don't want to use regex for this. Try out something like SimpleXML
EDIT
Well, why don't you start with this:
EDIT 2
Despite the fact that some of the answers posted using regular expression MAY work, you should get in the habit of using the correct tool for the job and regular expressions are not the correct tool for parsing of XML.
I think this is what you're looking for:
?>
If your array has a lot of elements dont use the count() function in the for loop, calculate the value first and then use it as a constant.
This is rather simple, can be solved by regex. Should be:
Regards
rbo
I'm using your
$content
variable: