PHP xmlreader to array
The following test function reads an XML file with PHP's xmlreader and returns a 2 dimensional array of 3 values ("id" = key).
How can you edit the code so that the username key and value is returned in the array also? (shown at the end)
ini_set('always_populate_raw_post_data', 'on');
function test()
{
$request = $HTTP_RAW_POST_DATA;
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$url = "http://site.xml";
$reader = new XMLReader();
$reader->open($url);;
$var = array();
$i = 0;
$limit = 3;
while ($reader->read())
{
if ($reader->name == "id" && $reader->nodeType == XMLReader::ELEMENT)
{
if ($i == $limit) break;
while ($reader->read())
{
if ($reader->nodeType == XMLReader::TEXT
|| $reader->nodeType == XMLReader::CDATA
|| $reader->nodeType == XMLReader::WHITESPACE
|| $reader->nodeType == XMLReader::SIGNIFICANT_WHITESPACE)
{
$var[$i]["id"] = $reader->value;
}
else if ($reader->nodeType == XMLReader::END_ELEMENT && $reader->name == "id")
{
break;
}
}
$i++;
}
}
$reader->close();
echo '<pre>';
print_r($var);
echo '</pre>';
}
test() returns this array
Array
(
[0] => Array
(
[id] => 345
)
[1] => Array
(
[id] => 123
)
[2] => Array
开发者_如何学编程 (
[id] => 789
)
)
How do you also get username key and value?
Array
(
[0] => Array
(
[id] => 345
[username] => name1
)
[1] => Array
(
[id] => 123
[username] => name2
)
[2] => Array
(
[id] => 789
[username] => name3
)
)
Add to Jose's answer
// needed to end element
else if ($reader->nodeType == XMLReader::END_ELEMENT && $reader->name == "username")
{
break;
}
This should work.
function test()
{
$request = $HTTP_RAW_POST_DATA;
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$url = "http://site.xml";
$reader = new XMLReader();
$reader->open($url);;
$var = array();
$i = 0;
$limit = 3;
while ($reader->read())
{
if (($reader->name == "id" || $reader->name == "username") && $reader->nodeType == XMLReader::ELEMENT)
{
$name = $reader->name;
if ($i == $limit) break;
while ($reader->read())
{
if ($reader->nodeType == XMLReader::TEXT
|| $reader->nodeType == XMLReader::CDATA
|| $reader->nodeType == XMLReader::WHITESPACE
|| $reader->nodeType == XMLReader::SIGNIFICANT_WHITESPACE)
{
$var[$i][$name] = $reader->value;
}
else if ($reader->nodeType == XMLReader::END_ELEMENT && $reader->name == "id")
{
break;
}
}
if($name == "username")
$i++;
}
}
$reader->close();
echo '<pre>';
print_r($var);
echo '</pre>';
}
CHANGES:
($reader->name == "id" || $reader->name == "username")
$name = $reader->name;
$var[$i][$name] = $reader->value;
if($name == "username") $i++;
if ($reader->name == "id" && $reader->nodeType == XMLReader::ELEMENT)
You need to have reader also check for
$reader->name == "username"
Right now you are only reading the ID. You have to also read the Username from the XML. Once you are also reading the username, you can add that to your array as well.
精彩评论