In a previous question I asked how to extract values from a XML file and put them into an array.
PHP xmlreader - values to array question
When using simpleXML, I was unable to read the XML file without errors being returned. I can only assume the XML file contains some bad characters because the file was successfully read with PHP XMLreader with the encoding set to ISO-8859-1.
Ideally I'd like to use simpleXML because looping seems simpler, but XMLreader seems to work.
- Is there a way to set encoding of an XML file for simpleXML?
2. If using XMLreader, how can you revise the code from my previous question add values to array only when a particular value in an element is found?
Example: Current code from previous question grabs all id
and username
.
only when [ title ] = value
<!-- X开发者_运维百科ML File -->
<?xml version="1.0" encoding="UTF-8"?>
<working version="2.0">
<group name="test">
<userdata>
<title>data</title>
<id>data</id>
<username>data</username>
</userdata>
</group>
</working>
There is no way to use anything other than UTF-8 with SimpleXML. However, since SimpleXML is just an easier way to use DOM, you could switch to using DOM instead. In fact, what you want would be pretty simple in DOM. Change '%%something%%'
to what you want to match (e.g., 'administrator'
).
<?php
$xml = new DOMDocument( "1.0", "ISO-8859-1" );
$xml->load("path/to/file.xml");
$xpath = new DOMXPath( $xml );
$nodes = $xpath->query( "/working/group/userdata[ title = '%%something%%' ]" );
$array = array();
foreach( $nodes as $k => $node )
{
foreach( $node->childNodes as $cnode )
{
$array[ $k ][ $cnode->nodeName ] = $cnode->textContent;
}
}
?>
Please note: Both DOM and SimpleXML load the entire document into memory before they are able to process against it. Because of this, if your document is large than the available memory to PHP (see ini setting of memory_limit
), you will need to use XMLReader or XMLWriter in these extreme cases.
Also note, I didn't test this but it should be pretty damn close to what you need. And if you also want an XMLReader example of this, let me know. It was just faster to use DOM for me :P
精彩评论