2014-09-30 29 views
0

我想从Web文档中提取两个值。值为api_keyauthenticity_token。我已经写了一个函数,但问题是它只是拉出api_key。有人能帮助我与另一片这个功能,这将使我拉出authenticity_token,感谢:PHP DOMDocument:当一个值没有ID值时,如何从网页中提取两个(2)值

这是我为我的功能代码:

<?php 
class apiKey{ 
    public $apikey; 
    public $authenticity_token; 


    function getApiKey(){ 
     //Get api_key and pass it in 
     $apikey = null; 
     $doc = new DOMDocument(); 
     $semcatStartUrl = 'https://entryform.semcat.net/1800stonewall'; 
     libxml_use_internal_errors(true); 
     $doc->loadHTMLFile("$semcatStartUrl"); 
     libxml_clear_errors(); 
     $apikey = $doc->getElementById('api_key')->getAttribute('value'); 
     return $apikey; 

    } 

    function getAuthenticityToken(){ 
     //My guesstimate this doesn’t work because the form hasn’t been/    //submitted yet 
     $authenticity_token = $_POST['authenticity_token']; 
     return $authenticity_token; 
    } 

} 


?> 

任何帮助将不胜感激。再次感谢!

回答

0

真实性令牌包含在此元素:

<input name="authenticity_token" type="hidden" value="..." /> 

不幸的是,你可以看到,这个元素没有ID属性,因此它越来越会稍微复杂一些。

$xpath = new DOMXPath($doc); 
$input = $xpath->query("input[@name=authenticity_token]")->item(0)->getAttribute("value"); 

理想情况下,你会希望在那里一些错误检查,以确保该元素存在,但是这个代码应该可以正常工作......只要是在同一个地方作为你现有的“获得API密钥”功能,因为它使用$doc

+0

做了一些细微的改动我会在回答中发布整个工作代码。感谢你的帮助,使我朝着正确的方向前进。 – LOwens1931 2014-09-30 17:10:04

0

下面是完整的工作代码:

<?php 
class apiKey{ 
    public $apikey; 
    public $authenticity_token; 


    function getApiKey(){ 
     //Get api_key and pass it in 
     $apikey = null; 
     $authenticity_token = null; 
     $doc = new DOMDocument(); 
     $semcatStartUrl = 'https://entryform.semcat.net/1800stonewall'; 
     libxml_use_internal_errors(true); 
     $doc->loadHTMLFile("$semcatStartUrl"); 
     libxml_clear_errors(); 
     $apikey = $doc->getElementById('api_key')->getAttribute('value'); 

     //Original 2 Lines 
     //$xpath = new DOMXPath($doc); 
     //$input = $xpath->query("input[@name=authenticity_token]")->item(0)->getAttribute("value"); 

      //Modified 2 Lines and added 2 Lines 
     $xpath = new DOMXPath($doc);  
     $input = $xpath->query("//input[@name='authenticity_token']"); 
     $authenticity_token = $input->item(0)->getAttribute('value'); 
     $this->authenticity_token = $authenticity_token; 

     return $apikey; 

    } 

    function getAuthenticityToken(){ 

       return $this->authenticity_token; 
    } 

} 


?> 

就像一个伟大的程序员!谢谢您的帮助。它确实有助于我指出正确的方向,在做了一些研究和测试之后,我可以对代码进行一些细微的更改,使其成功运行,无错误。

相关问题