簡體   English   中英

幫我 xml 解析 php

[英]Help me xml parsing in php

我收到了來自 zoho 招募 API 的 xml 回復。 我只需要解析它得到一些屬性和節點的值(不管你怎么稱呼它)。 然后更新它們並提交回來。 xml 如下所示。 就像如果我想檢查什么是名字,它應該返回 TEst1,當我想更新它時,我應該得到更新,然后我必須以字符串格式保存它。 幫我解決這個問題。

<?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   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>

SimpleXML (通常內置在 PHP 5 中)或 PHP 手冊中列出的任何其他 XML 庫應該可以幫助您。

請注意,我將<FL val="Role (if "Other")">更改為 <FL val="Role (if "Other")" <FL val="Role (if &quot;Other&quot;)">以便形成良好的 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 你有 XML 作為 Object 並且可以迭代實體:

$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";
    }
}

這取決於你想如何做到這一點。 您可以在服務器端執行此操作,也可以使用 javascript 執行此操作。 在服務器端的情況下,您可以嘗試使用 PHP..here is an article about it 在 javascript 中,您可以通過打開 xml 文件然后調用 XMLhttprequest 來檢索對 Z38086BB093DB936 文件中的 DOM 元素的訪問來完成此操作:

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;

上面的代碼將打開 XML 文件,XML 文件將包含文件的 DOM 信息的響應發送回 xmlDoc..

你為什么不展示你到目前為止所做的事情,因為我們可以通過這種方式更好地幫助你

使用此代碼

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM