2011-06-07 167 views
0

我有一个来自zoho recruit API的xml响应。我只需要解析它就可以得到一些属性和节点的值(不管你怎么称呼它)。然后更新它们并提交回来。下面给出了xml。 像如果我想检查什么是名字,它应该返回TEst1 ,当我想更新它时,我应该更新,然后我必须将其保存为字符串格式。 帮我弄清楚这一点。帮我在php中解析xml解析

<?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[[email protected]]]></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> 
+1

你是否已经尝试过什么吗? – deceze 2011-06-07 05:27:08

+0

是的,但我找不出任何东西。互联网上的所有例子都使用不同的xml格式。所以他们不工作我的XML文件。 – 2011-06-07 05:29:11

+2

您知道,XML的概念是它们可以完全不同。您使用的是什么XML解析器? SimpleXML可能是一个开始 – konsolenfreddy 2011-06-07 05:29:15

回答

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[[email protected]]]></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())); 

?> 
+0

你是一个天才...感谢这只是工作像我想要的。非常感谢。 – 2011-06-07 06:13:03

+0

freddy K.的帖子引起了我注意自PHP 5.1以来可用的LIBXML_NOCDATA参数,我将其纳入代码中,因为它更清晰(并且CDATA替换代码遭受preg_replace中的PHP怪癖,它将反斜杠添加到带引号的引号中'e'修饰符 - 你可以去掉它,但它会变得麻烦和容易出错)。我强烈建议使用我的修改代码。 – 2011-06-07 06:39:25

+0

您能否告诉我如何添加新节点,如我想在此xml中添加<![CDATA [TEst3]]>。告诉我如何在上面的xml文件中添加这个。 – 2011-06-10 06:14:27

3

SimpleXML(通常内置到PHP 5)或任何PHP手册中列出的other XML libraries应该帮助你。

+0

请给我一个小例子我尝试了一切在php.net,w3schools和其他网站上阅读。但他们不能在我的XML上工作。 – 2011-06-07 05:33:55

+0

您可以使用[simplexml_load_file](http://www.php.net/manual/en/function.simplexml-load-file.php)加载文件,也可以使用类的构造函数从字符串加载文件。然后,您可能需要使用[children](http://www.php.net/manual/en/simplexmlelement.children.php)方法迭代子节点,或者使用[xpath](http ://www.php.net/manual/en/simplexmlelement.xpath.php)方法来获得你想要的元素。 – BlackBulletIV 2011-06-07 05:41:51

1

这取决于你想如何做到这一点。你可以做到服务器端,或者你可以使用JavaScript来做到这一点。在服务器端的情况下,你可以尝试使用PHP ..这是一个article about it

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文件将发送:在JavaScript中,您可以通过打开XML文件,然后调用XMLHttpRequest来获取访问XML文件中的DOM元素做响应包含文件回到xmlDoc中的DOM信息..

你为什么不告诉你,你已经完成的工作是什么,因为我们可以帮助您更好地这样

+0

埃姆,也许他需要一个PHP解决方案,而不是一个JavaScript的...;) – Eineki 2011-06-07 05:44:13

+0

我的坏,没有看到PHP标签。有很多关于XML解析PHP的在线参考资料,我认为他的问题将很快得到解决.. – 2011-06-07 05:50:42

+0

是啊我得到它的工作由brettz9提供的代码 – 2011-06-07 12:08:51

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[[email protected]]]></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"; 
    } 
} 
+0

感谢您的解决方案也非常好。我将它与brettz9的解决方案结合使用。再次感谢。 – 2011-06-07 06:54:39

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