PDA

View Full Version : Passing xml tree to php



r0000
August 10th, 2008, 09:36 PM
Basicaly I'm passing xml tree to php and having php insert it into a db, no luck yet, I'm not sure where i'm going wrong with this.
Thanks for any help with this.

Here's the code i'm using.

//AS3
var team_xml:XML = new XML(

<league>
<teams>
<team>Team 1</team>
<team>Team 1</team>
</teams>
</league>

);

var request:URLRequest = new URLRequest("testing.php");
request.method = URLRequestMethod.POST;

var variables:URLVariables = new URLVariables();
variables.xml = team_xml;

request.data = variables;
var loader:URLLoader = new URLLoader();

loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, teamReturn);
loader.load(request);


//PHP
<?php

$sx = $_POST['xml'];

//DB Connection -------------------------------------------------------------------------------------------------
$dbhost = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$dbname = "xxx";

$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die("Could not connect to host.");
mysqli_select_db($connection, $dbname) or die ("Error");

foreach ($sx->team as $team){

$teamname = $team->teamname;
mysqli_query($connection, "INSERT INTO teams (teamname) VALUES ('$teamname')");

}

echo "xml=Done";

?>

wvxvw
August 11th, 2008, 03:46 AM
These are the places which look confusing:

var team_xml:XML = new XML(

<league>
<teams>
<team>Team 1</team>
<team>Team 1</team>
</teams>
</league>

);
[Probably, you meant:

var team_xml:XML =
<league>
<teams>
<team>Team 1</team>
<team>Team 1</team>
</teams>
</league>;


foreach ($sx->team as $team){
$sx is a string, and foreach is used on arrays. Try putting

error_reporting(E_ALL);on evey your php page. This will output the error messages if there ware any in your PHP script.
The most common syntax for iterating through the array would be this:

foreach ($array as $i => $value) {
print $array[$i] . " == " . $value;
}
where $array is an array you want to iterate through, $i the iterator, $value the value of the array at the iterator position. $i may be either string or integer.
If you want $sx to be an XML object you have to use either SimpleXML (http://il2.php.net/manual/en/book.simplexml.php) class or DOMDocument (http://il2.php.net/manual/en/class.domdocument.php) class. And parse the string into one of the. For working with XML in PHP see the reference for those classes.

r0000
August 11th, 2008, 11:41 AM
Got it to work this way

<?php

//$dom = $_POST['xml'];

$xml = '<laegue>
<team>
<teamname>Giants</teamname>
</team>
<team>
<teamname>Eagles</teamname>
</team>
</laegue>';

$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml);

foreach ($dom->getElementsByTagname('team') as $team){

$teamname = $team->getElementsByTagname('teamname');
$team_name = $teamname->item(0)->firstChild->nodeValue;
print "$team_name";

}

?>