عندي كتاب ممتاز أزكيه لك،
اسمه XML and PHP المؤلف Vikram Vaswani ...
الحقيقة ما فهمت طريقة تعامل php مع xml إلا بعد قراءة الكتاب و الأمثلة اللي فيه.
شف هذا مثال بسيطمأخوذ من برنامج المنتديات الفيبوليتين، أضفت عليه تعليقات وبسطته عشان أستوعبه... هذا الملف هو اللي يتعامل مع ملفات اللغة في الفيبوليتين:
كود PHP:
<?
// ############### Handling Opening Tags ############### //
function start_element($parser,$name,$attrs)
//$parser is the XML parser (php use Expat library (SAX parser)).
//$name is the element's name (opening tag name).
//$attrs is an array that holds all the attributes of $name.
{
global $arr, $SentenceType, $SentenceName, $NumOfSentences;
//$arr is a 2d array that stores all sentences
switch ($name)
{
case ("language"):
$langinfo['title'] = $attrs['name'];
$langinfo['quranirversion'] = $attrs['quranirversion'];
$langinfo['ismaster']= ($attrs['type'] == 'master');
$SentenceName = false;
break;
case ("sentencetype"):
$SentenceType = $attrs['name'];
$arr["$SentenceType"] = array();
$SentenceName = false;
break;
case ("sentence"):
$NumOfSentences++;
$SentenceName = $attrs['name'];
$arr["$SentenceType"]["$SentenceName"] = '';
break;
default:
echo "Unknown tag ";
}
}
// ############### Handling Closing Tags ############### //
function end_element($parser,$name)
{
global $cdata,$SentenceName;
$cdata=trim($cdata); //Removing trailing and preceeding white spaces from cdata
switch ($name)
{
case ("language"):
$SentenceName=false;
break;
case ("sentencetype"):
$SentenceName=false;
break;
case ("sentence"):
$SentenceName=false;
break;
default:
echo "Warning: Unknown tag was placed wrong";
}
}
// ############### Handling CData ############### //
function cdata($parser,$data)
{
global $arr, $SentenceType, $SentenceName;
if ($SentenceName)
{
$arr["$SentenceType"]["$SentenceName"] .= $data;
}
}
// ############### Start parsing XML Language File, using the above handlers and PHP functions ############### //
$file="data.xml"; //Name of the language file
$parser=xml_parser_create("UTF-8"); //Creating the xml parser, encoding is optional.
xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,false); //Making XML case-insisitive
xml_set_element_handler($parser, "start_element", "end_element");
xml_set_character_data_handler($parser,"cdata");
$fp = @fopen($file,"r") or die("Could not locate the language file $file, or you might not have the permission to run it!");
while ($xml_input=fread($fp,4096)) //Reading the XML file
{
$ok=xml_parse($parser,$xml_input,feof($fp));
if (!$ok) //Display an error message about parsing the XML file
die(sprintf("Error in $file: '%s' at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));
}
xml_parser_free($parser); //Stop and release the parser (clean it up)
?>
ولاحظ في الأخير الدالة xml_set_element_handler، و هي من أهم الدوال، و القيم اللي تأخذها عبارة عن دوال أيضا و هي اللي عرفناها في بداية البرنامج