开发者

Help me xml parsing in php

I have an xml response from zoho recruit API. I just need to parse it get values of a few attributes and nodes(whatever you call it). And then update them and submit back. The xml is given below. Like If i want to check what is first name it should return TEst1 and when I want to update it I should get updated and then I have to save it in a string format. Help me to figure this out.

<?xml version="1.0" encoding="UTF-8" ?>

<response uri="/ats/private/xml/Candidates/getRecords">
<result>
<Candidates>
<row no="1">
<FL val="RESUMEID"><![CDATA[93327000000109297]]></FL>
<FL val="Modified by"><![CDATA[Not specified]]></FL>
<FL val="Modified time"><![CDATA[Yesterday]]></FL>
<FL val="Candidate ID"><![CDATA[677]]></FL>
<FL val="First name"><![CDATA[TEst1]]></FL>
<FL val="Last name"><![CDATA[TEst2]]></FL>
<FL val="Residental Address"><![CDATA[TESTing res address]]></FL>
<FL val="Email ID"><![CDATA[test1@email.com]]></FL>
<FL val="Mobile Phone"><![CDATA[123456789]]></FL>
<FL val="Created On"><![CDATA[Yesterday]]></FL>
<FL val="Owner"><![CDATA[0]]></FL>
<FL val="Source"><![CDATA[Embed]]></FL>
<FL val="Employment Preference"><![CDATA[Contract (Full Time), Permanent (Full Time), Contract (Part Time), Permanent (Part Time)]]></FL>
<FL val="Cover Letter" type="url" url="https://recruit.zoho.com/ats/viewPhoto?filename=tVmTJJk2PIGQSgJSgY2fTzZfMgYE*W1ZBQ.KWiE6q68UOoUiAiY8ElcJtvxybS4bvD4mCWuA8aE-"><![CDATA[samplecoverletter.txt]]></FL>
<FL val="Total work exp (year)"><![CDATA[10]]></FL>
<FL val="Current Role"><![CDATA[Administrative Officer]]></FL>
<FL val="Current Role if Other"><![CDATA[current_role_if_other]]></FL>
<FL val="Current Employer/Customer"><![CDATA[Current_employer_name]]></FL>
<FL val="Skill sets"><![CDATA[skill_sets_goes_here]]></FL>
<FL val="Roles"><![CDATA[Consultant, 93327000000068819, Administrative Officer, Application Developer, Business Analyst, Change Manager, Business Development, Chief Technology Officer, Chief Information Officer, Chief Executive Officer, Data Analyst, Director, IT Manager, Implementation Mgr, Functional Analyst, PMO Manager, Other, Network Admin, Portfolio Manager, Program Manager, Project Admin, Project Manager (Jnr), Project Lead, Project Director, Project Manager (Mid), Project Manager (Snr/Principal), Project Officer, Project Scheduler, Service Delivery Mgr, Release Manager, Quality Manager, Solutions Architect, Systems / Technical Analyst, Systems Administrator, Technical Support, Technical Architect, Systems Engineer, Test Analyst, Test Manager]]></FL>
<FL val="Role (if "Other")"><![CDATA[Role_other]]></FL>
<FL val="Industries"><![CDATA[93327000000068909, 93327000000070037, Aviation, Consulting, Contact Centres, Construction / Engineering, Council, Defense, Education, Energy, Finance/Banking, Gaming, Government, Health / Medical, Hospitality, ICT, Insurance, Manufacturing, Media, Mining, Other, Rail, Retail, Phamacetical, Telecommunications, Transportation, Utilities]]></FL><FL val="Expected Rate/Salary"><![CDATA[147852369]]></FL>
<FL val="Qualifications, Credentials, Memberships"><![CDATA[93327000000068871, 93327000000101075, AABA Membership, Agile PM Certification, AIPM   Membersh开发者_StackOverflowip, CMI Membership, Degree, IIBA Membership, ITIL, Masters Degree, MBA, MSP, PMI Membership, PMP, PRINCE2, RegPM]]></FL>
<FL val="Additional Information"><![CDATA[addational_information_goes_here]]></FL>
<FL val="Attach resume" type="url" url="https://recruit.zoho.com/ats/viewPhoto?filename=tVmTJJk2PIGQSgJSgY2fTzZfMgYE*W1ZBQ.KWiE6q69pGZ2uc5*.nlcJtvxybS4bvD4mCWuA8aE-"><![CDATA[sampleresume.txt]]></FL>
<FL val="Photo (for CV)" type="url" url="https://recruit.zoho.com/ats/viewPhoto?filename=tVmTJJk2PIGQSgJSgY2fTzZfMgYE*W1ZBQ.KWiE6q685xDP3Iw.5GlcJtvxybS4bvD4mCWuA8aE-"><![CDATA[microsoft-gold-partner.png]]></FL>
<FL val="Candidate status"><![CDATA[New]]></FL></row></Candidates></result></response>


Note that I changed <FL val="Role (if "Other")"> to <FL val="Role (if &quot;Other&quot;)"> in order to be well-formed XML:

<?php

$result = <<<HERE
<?xml version="1.0" encoding="UTF-8" ?>

<response uri="/ats/private/xml/Candidates/getRecords">
<result>
<Candidates>
<row no="1">
<FL val="RESUMEID"><![CDATA[93327000000109297]]></FL>
<FL val="Modified by"><![CDATA[Not specified]]></FL>
<FL val="Modified time"><![CDATA[Yesterday]]></FL>
<FL val="Candidate ID"><![CDATA[677]]></FL>
<FL val="First name"><![CDATA[TEst1]]></FL>
<FL val="Last name"><![CDATA[TEst2]]></FL>
<FL val="Residental Address"><![CDATA[TESTing res address]]></FL>
<FL val="Email ID"><![CDATA[test1@email.com]]></FL>
<FL val="Mobile Phone"><![CDATA[123456789]]></FL>
<FL val="Created On"><![CDATA[Yesterday]]></FL>
<FL val="Owner"><![CDATA[0]]></FL>
<FL val="Source"><![CDATA[Embed]]></FL>
<FL val="Employment Preference"><![CDATA[Contract (Full Time), Permanent (Full Time), Contract (Part Time), Permanent (Part Time)]]></FL>
<FL val="Cover Letter" type="url" url="https://recruit.zoho.com/ats/viewPhoto?filename=tVmTJJk2PIGQSgJSgY2fTzZfMgYE*W1ZBQ.KWiE6q68UOoUiAiY8ElcJtvxybS4bvD4mCWuA8aE-"><![CDATA[samplecoverletter.txt]]></FL>
<FL val="Total work exp (year)"><![CDATA[10]]></FL>
<FL val="Current Role"><![CDATA[Administrative Officer]]></FL>
<FL val="Current Role if Other"><![CDATA[current_role_if_other]]></FL>
<FL val="Current Employer/Customer"><![CDATA[Current_employer_name]]></FL>
<FL val="Skill sets"><![CDATA[skill_sets_goes_here]]></FL>
<FL val="Roles"><![CDATA[Consultant, 93327000000068819, Administrative Officer, Application Developer, Business Analyst, Change Manager, Business Development, Chief Technology Officer, Chief Information Officer, Chief Executive Officer, Data Analyst, Director, IT Manager, Implementation Mgr, Functional Analyst, PMO Manager, Other, Network Admin, Portfolio Manager, Program Manager, Project Admin, Project Manager (Jnr), Project Lead, Project Director, Project Manager (Mid), Project Manager (Snr/Principal), Project Officer, Project Scheduler, Service Delivery Mgr, Release Manager, Quality Manager, Solutions Architect, Systems / Technical Analyst, Systems Administrator, Technical Support, Technical Architect, Systems Engineer, Test Analyst, Test Manager]]></FL>
<FL val="Role (if &quot;Other&quot;)"><![CDATA[Role_other]]></FL>
<FL val="Industries"><![CDATA[93327000000068909, 93327000000070037, Aviation, Consulting, Contact Centres, Construction / Engineering, Council, Defense, Education, Energy, Finance/Banking, Gaming, Government, Health / Medical, Hospitality, ICT, Insurance, Manufacturing, Media, Mining, Other, Rail, Retail, Phamacetical, Telecommunications, Transportation, Utilities]]></FL><FL val="Expected Rate/Salary"><![CDATA[147852369]]></FL>
<FL val="Qualifications, Credentials, Memberships"><![CDATA[93327000000068871, 93327000000101075, AABA Membership, Agile PM Certification, AIPM   Membership, CMI Membership, Degree, IIBA Membership, ITIL, Masters Degree, MBA, MSP, PMI Membership, PMP, PRINCE2, RegPM]]></FL>
<FL val="Additional Information"><![CDATA[addational_information_goes_here]]></FL>
<FL val="Attach resume" type="url" url="https://recruit.zoho.com/ats/viewPhoto?filename=tVmTJJk2PIGQSgJSgY2fTzZfMgYE*W1ZBQ.KWiE6q69pGZ2uc5*.nlcJtvxybS4bvD4mCWuA8aE-"><![CDATA[sampleresume.txt]]></FL>
<FL val="Photo (for CV)" type="url" url="https://recruit.zoho.com/ats/viewPhoto?filename=tVmTJJk2PIGQSgJSgY2fTzZfMgYE*W1ZBQ.KWiE6q685xDP3Iw.5GlcJtvxybS4bvD4mCWuA8aE-"><![CDATA[microsoft-gold-partner.png]]></FL>
<FL val="Candidate status"><![CDATA[New]]></FL></row></Candidates></result></response>
HERE;

// First deal with problem with Simple XML and CDATA
$sxo = simplexml_load_string($result, null, LIBXML_NOCDATA);

// Use these two lines instead of the above line if you are forced to use PHP < 5.1.0 or LibXML < 2.6.0
// $result = preg_replace("/\<\!\[CDATA\[(.*?)\]\]\>/ies", 'htmlspecialchars("$1")', $result);
// $sxo = simplexml_load_string($result);


// Find First name
$fn = $sxo->xpath('//FL[@val="First name"]');

// Set the child content
$fn[0][0] = "Here's a new name";

// Show XML
print_r(htmlentities($sxo->asXML()));

?>


SimpleXML (usually built into PHP 5) or any of the other XML libraries listed in the PHP manual should help you out.


Using SimpleXML you have the XML as Object and can iterate over the entities:

$test = '<?xml version="1.0" encoding="UTF-8" ?>

<response uri="/ats/private/xml/Candidates/getRecords">
<result>
<Candidates>
<row no="1">
<FL val="RESUMEID"><![CDATA[93327000000109297]]></FL>
<FL val="Modified by"><![CDATA[Not specified]]></FL>
<FL val="Modified time"><![CDATA[Yesterday]]></FL>
<FL val="Candidate ID"><![CDATA[677]]></FL>
<FL val="First name"><![CDATA[TEst1]]></FL>
<FL val="Last name"><![CDATA[TEst2]]></FL>
<FL val="Residental Address"><![CDATA[TESTing res address]]></FL>
<FL val="Email ID"><![CDATA[test1@email.com]]></FL>
<FL val="Mobile Phone"><![CDATA[123456789]]></FL>
<FL val="Created On"><![CDATA[Yesterday]]></FL>
<FL val="Owner"><![CDATA[0]]></FL>
<FL val="Source"><![CDATA[Embed]]></FL>
<FL val="Employment Preference"><![CDATA[Contract (Full Time), Permanent (Full Time), Contract (Part Time), Permanent (Part Time)]]></FL>
<FL val="Cover Letter" type="url" url="https://recruit.zoho.com/ats/viewPhoto?filename=tVmTJJk2PIGQSgJSgY2fTzZfMgYE*W1ZBQ.KWiE6q68UOoUiAiY8ElcJtvxybS4bvD4mCWuA8aE-"><![CDATA[samplecoverletter.txt]]></FL>
<FL val="Total work exp (year)"><![CDATA[10]]></FL>
<FL val="Current Role"><![CDATA[Administrative Officer]]></FL>
<FL val="Current Role if Other"><![CDATA[current_role_if_other]]></FL>
<FL val="Current Employe Customer"><![CDATA[Current_employer_name]]></FL>
<FL val="Skill sets"><![CDATA[skill_sets_goes_here]]></FL>
<FL val="Roles"><![CDATA[Consultant, 93327000000068819, Administrative Officer, Application Developer, Business Analyst, Change Manager, Business Development, Chief Technology Officer, Chief Information Officer, Chief Executive Officer, Data Analyst, Director, IT Manager, Implementation Mgr, Functional Analyst, PMO Manager, Other, Network Admin, Portfolio Manager, Program Manager, Project Admin, Project Manager (Jnr), Project Lead, Project Director, Project Manager (Mid), Project Manager (Snr/Principal), Project Officer, Project Scheduler, Service Delivery Mgr, Release Manager, Quality Manager, Solutions Architect, Systems / Technical Analyst, Systems Administrator, Technical Support, Technical Architect, Systems Engineer, Test Analyst, Test Manager]]></FL>
<FL val="Role (if Other)"><![CDATA[Role_other]]></FL>
<FL val="Industries"><![CDATA[93327000000068909, 93327000000070037, Aviation, Consulting, Contact Centres, Construction / Engineering, Council, Defense, Education, Energy, Finance/Banking, Gaming, Government, Health / Medical, Hospitality, ICT, Insurance, Manufacturing, Media, Mining, Other, Rail, Retail, Phamacetical, Telecommunications, Transportation, Utilities]]></FL><FL val="Expected Rate/Salary"><![CDATA[147852369]]></FL>
<FL val="Qualifications, Credentials, Memberships"><![CDATA[93327000000068871, 93327000000101075, AABA Membership, Agile PM Certification, AIPM   Membership, CMI Membership, Degree, IIBA Membership, ITIL, Masters Degree, MBA, MSP, PMI Membership, PMP, PRINCE2, RegPM]]></FL>
<FL val="Additional Information"><![CDATA[addational_information_goes_here]]></FL>
<FL val="Attach resume" type="url" url="https://recruit.zoho.com/ats/viewPhoto?filename=tVmTJJk2PIGQSgJSgY2fTzZfMgYE*W1ZBQ.KWiE6q69pGZ2uc5*.nlcJtvxybS4bvD4mCWuA8aE-"><![CDATA[sampleresume.txt]]></FL>
<FL val="Photo (for CV)" type="url" url="https://recruit.zoho.com/ats/viewPhoto?filename=tVmTJJk2PIGQSgJSgY2fTzZfMgYE*W1ZBQ.KWiE6q685xDP3Iw.5GlcJtvxybS4bvD4mCWuA8aE-"><![CDATA[microsoft-gold-partner.png]]></FL>
<FL val="Candidate status"><![CDATA[New]]></FL>
</row>
</Candidates>
</result>
</response>';

$xml = simplexml_load_string($test, null, LIBXML_NOCDATA);

foreach($xml->result->Candidates as $candidate){
    foreach($candidate->row->FL as $FL){
        print "Attributes:\n";
        foreach($FL->attributes() as $attribute => $value){
            print $attribute .':'.$value."\n";
        }
        print "Value:\n";
        print (string)$FL."\n";
    }
}


It depends on how you want to do this. You can do it server-side or you can do it using javascript. In case of server side, you can try doing it by using PHP..here is an article about it. In javascript, you do it by opening the xml file and then calling the XMLhttprequest to retrieve access to the DOM elements in the XML file :

if (window.XMLHttpRequest)
  xmlhttp=new XMLHttpRequest();//for IE7+, Firefox, Chrome, Opera, Safari
else
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");//for IE

xmlhttp.open("GET","your_file.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

That code above will open the XML file and the XML file will send a response containing the DOM info of the file back to xmlDoc..

Why dont you show what you have done so far since we can help you better that way


Use this code

function xml2array($contents, $get_attributes=1, $priority = 'tag') {
    if(!$contents) return array();

    if(!function_exists('xml_parser_create')) {
        //print "'xml_parser_create()' function not found!";
        return array();
    }

    //Get the XML parser of PHP - PHP must have this module for the parser to work
    $parser = xml_parser_create('');
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);

    if(!$xml_values) return; //Hmm...

    //Initializations
    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();

    $current = &$xml_array; //Refference

    //Go through the tags.
    $repeated_tag_index = array(); //Multiple tags with same name will be turned into an array
    foreach($xml_values as $data) {
        unset($attributes,$value); //Remove existing values, or there will be trouble

        //This command will extract these variables into the foreach scope
        // tag(string), type(string), level(int), attributes(array).
        extract($data); //We could use the array by itself, but this cooler.

        $result = array();
        $attributes_data = array();

        if(isset($value)) {
            if($priority == 'tag') $result = $value;
            else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
        }

        //Set the attributes too.
        if(isset($attributes) and $get_attributes) {
            foreach($attributes as $attr => $val) {
                if($priority == 'tag') $attributes_data[$attr] = $val;
                else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
            }
        }

        //See tag status and do the needed.
        if($type == "open") { //The starting of the tag ''
            $parent[$level-1] = &$current;
            if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
                $current[$tag] = $result;
                if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
                $repeated_tag_index[$tag.'_'.$level] = 1;

                $current = &$current[$tag];

            } else { //There was another element with the same tag name

            if(isset($current[$tag][0])) { //If there is a 0th element it is already an array
                $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                $repeated_tag_index[$tag.'_'.$level]++;
            } else { //This section will make the value an array if multiple tags with the same name appear together
                $current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
                $repeated_tag_index[$tag.'_'.$level] = 2;

                if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
                    $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                    unset($current[$tag.'_attr']);
                }

            }
            $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
            $current = &$current[$tag][$last_item_index];
        }

    } elseif($type == "complete") { //Tags that ends in 1 line ''
        //See if the key is already taken.
        if(!isset($current[$tag])) { //New Key
        $current[$tag] = $result;
        $repeated_tag_index[$tag.'_'.$level] = 1;
        if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;

        } else { //If taken, put all things inside a list(array)
            if(isset($current[$tag][0]) and is_array($current[$tag])) { //If it is already an array...

            // ...push the new element into that array.
            $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;

            if($priority == 'tag' and $get_attributes and $attributes_data) {
                $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
            }
            $repeated_tag_index[$tag.'_'.$level]++;

            } else { //If it is not an array...
                $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
                $repeated_tag_index[$tag.'_'.$level] = 1;
                if($priority == 'tag' and $get_attributes) {
                    if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well

                    $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                    unset($current[$tag.'_attr']);
                }

                if($attributes_data) {
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                    }
                }
                $repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken
                }
            }
        } elseif($type == 'close') { //End of tag ''
        $current = &$parent[$level-1];
        }
    }
    return($xml_array);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜