Aşağıdaki test fonksiyonu PHP'nin xmlreader bir XML dosyasını okur ve 3 değerleri ("id" = anahtar) 2 boyutlu bir dizi döndürür.
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;
}