Page 1 of 1

simplexml_load_file with 2 array

Posted: Wed Jul 25, 2012 7:31 pm
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

:)

Re: simplexml_load_file with 2 array

Posted: Sat Jul 28, 2012 4:26 am
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;
?>