simplexml_load_file with 2 array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
srdva59
Forum Commoner
Posts: 77
Joined: Sun Feb 15, 2009 10:58 am

simplexml_load_file with 2 array

Post by srdva59 »

hi,
try load a xml with this struture:


<file>
<one>

<a> test </a>

<array>
<arra1> silver </arra1>
</array>


</one>

<one>

<a> test </a>

<array>
<arra1> silver </arra1>
</array>

</one>

</file>


i can load all values except the values that is inside of the array


foreach($xml->children() as $child) {


echo $child->a; //with this i can receive the value test



}


but i need load the array->arra1 too.
i can i do that? thanks for your help

:)
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: simplexml_load_file with 2 array

Post by social_experiment »

I'll explain at the hand of the example xml file below

Code: Select all

<?xml version="1.0" ?>
<bananaNews>
	<newsitem type="world">
		<headline>Banana sales reach an all time high</headline>		
		<byline>William Curvey</byline>
		<article>
			<text>This is article text</text>
		</article>
		<article>
			<text>This is article text. More</text>
		</article>
	</newsitem>	
	
	<newsitem type="world">
	<headline>Banana sales increase ten-fold</headline>		
	<byline>Charles Split</byline>
	<article>
		<text>Random text.</text>
	</article>
	<article>
		<text>Arbitrary text here.</text>
	</article>
	</newsitem>	
</bananaNews>
The code below will return "This is article text"

Code: Select all

<?php
 echo $xml->newsitem[0]->article[0]->text;
?>
Instead of using a foreach loop - try a for loop;

Code: Select all

<?php
 $xml = simplexml_load_file('file.xml');
 $total = count($xml->newsitem);
 for ($i=0; $i<$total; $i++) {
    // loop through
 }
?>
With regards to your question to access the value in <arra1> you would use

Code: Select all

<?php
 // will return 'silver' from the first 'one' element
 $xml->one[0]->array->arra1;
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply