Would someone draw up a Q&D example of parsing XML into
Posted: Fri Oct 13, 2006 4:57 am
Just a quick script to get me started on parsing XML data into a PHP variable.
Regards,
Regards,
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
$xml = new SimpleXMLElement(file_get_contents('/path/to/xml/file.xml'));
echo $xml->someTag;Code: Select all
$newVar = $xml->stephen->age;I see it in the ManualOren wrote:And what is SimpleXMLElement d11wtq? I don't see it in the manual
Code: Select all
$xml = simplexml_load_file('data.xml');
while (list($k) = each ($xml)) {
echo $k;
}Code: Select all
break;Code: Select all
foreach ($xml->stephen->age as $value) {
echo $value;Code: Select all
$xml->ALL->ALLCode: Select all
$xml = simplexml_load_file('data.xml');
foreach ($xml->friend as $friend) {
printf("Name: %s <br> ", $friend->name);
printf("Age: %s <br> ", $friend->age);
}Oh yeah, I see it too now. I simply searched in the Function List (http://us2.php.net/manual-lookup.php?pa ... XMLElement) and couldn't find itd11wtq wrote:I see it in the Manualhttp://uk.php.net/simplexml I've never used it before, but it's on that page when you read the code examples.
Code: Select all
xml_set_element_handlerCode: Select all
<friends>
<friend>
<name> Stephen </name>
<age> 21 </name>
<sex> Male </name>
</friend>
<friend>
<name> Scott </name>
<age> 20 </age>
<sex> Male </age>
</friend>
<friend>
<name> Helena </name>
<age> 20 </age>
<sex> Female </sex>
</friend>
</friends>Code: Select all
xml_set_character_data_handlerCode: Select all
simplexml_load_fileCode: Select all
function tag_contents($parser, $data) {
if ($j =<4) {
switch ($i) {
case 0:
mysql_query("INSERT INTO test (name) VALUES ('$data')");
$i++;
$j++;
break;
case 1:
mysql_query("INSERT INTO test (age) VALUES ('$data')");
$i++;
$j++
break;
case 2:
mysql_query("INSERT INTO test (sex) VALUES ('$data')");
$i++;
$j++;
break;
}
else $j = 0;
}
}