帮我在php中解析xml

时间:2011-06-07 05:24:02

标签: php xml

我有来自zoho recruit 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>

5 个答案:

答案 0 :(得分:3)

SimpleXML(通常内置于PHP 5中)或PHP手册中列出的任何other XML libraries都可以帮助您。

答案 1 :(得分:3)

请注意,我将<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()));

?>

答案 2 :(得分:2)

使用SimpleXML,您可以将XML作为对象,并可以遍历实体:

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

答案 3 :(得分:1)

这取决于你想要怎么做。您可以在服务器端执行此操作,也可以使用javascript执行此操作。如果是服务器端,您可以尝试使用PHP来实现它。这是一个article about it。在javascript中,您可以通过打开xml文件然后调用XMLhttprequest来检索对XML文件中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 ..

为什么不展示你到目前为止所做的事情,因为我们可以更好地帮助你

答案 4 :(得分:1)

使用此代码

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