2011-03-19 36 views
3

好吧,我有這個php頁面在亞馬遜做了一個searchItem請求並獲取了一個產品列表。如何在PHP中使用簡單的xml對象

當我使用下面的代碼,訪問我看到一個XML格式的網頁頁面時(如Firefox一樣):

<?php 
    //in top of file: 
    header('Content-type: text/xml'); 

    // code 
    // code 

    $response = file_get_contents($SignedRequest); //doesn't matter what signerrequest is, it works 
    print $response; 
?> 

使用這個代碼上面,我得到一個良好的XML文件。不過,我想在我的PHP代碼的XML對象遍歷等等。所以我儘量用simplexml_load_string()函數是這樣的:

$response = file_get_contents($SignedRequest); 
$xml = simplexml_load_string($response); 

我現在要幾分姿色打印這個對象來查看XML結構。一些循環或什麼?

我怎樣才能看到我是否有一個XML對象,它的結構是什麼等。是否有某種simplexmlobjects的prettyprint函數?

+0

'print_r'應該SimpleXML的工作對象 – slhck 2011-03-19 21:23:37

+0

@slhck:它不打印的XML結構。 – BoltClock 2011-03-19 21:25:27

+0

是的print_r()也不是很清楚。不管怎麼說,還是要謝謝你! – Javaaaa 2011-03-19 21:28:07

回答

1

您可以嘗試此功能。我已經在xml文件上測試過它,它可以工作。 最初由Eric這個職位做:http://gdatatips.blogspot.com/2008/11/xml-php-pretty-printer.html

<?php 
/** Prettifies an XML string into a human-readable and indented work of art 
* @param string $xml The XML as a string 
* @param boolean $html_output True if the output should be escaped (for use in HTML) 
*/ 
function xmlpp($xml, $html_output=false) { 

    $xml_obj = new SimpleXMLElement($xml); 
    $level = 4; 
    $indent = 0; // current indentation level 
    $pretty = array(); 

    // get an array containing each XML element 
    $xml = explode("\n", preg_replace('/>\s*</', ">\n<", $xml_obj->asXML())); 

    // shift off opening XML tag if present 
    if (count($xml) && preg_match('/^<\?\s*xml/', $xml[0])) { 
     $pretty[] = array_shift($xml); 
    } 

    foreach ($xml as $el) { 
     if (preg_match('/^<([\w])+[^>\/]*>$/U', $el)) { 
      // opening tag, increase indent 
      $pretty[] = str_repeat(' ', $indent) . $el; 
      $indent += $level; 
     } else { 
      if (preg_match('/^<\/.+>$/', $el)) {    
       $indent -= $level; // closing tag, decrease indent 
      } 
      if ($indent < 0) { 
       $indent += $level; 
      } 
      $pretty[] = str_repeat(' ', $indent) . $el; 
     } 
    } 
    $xml = implode("\n", $pretty); 
    return ($html_output) ? htmlentities($xml) : $xml; 
} 
$xml = file_get_contents('graph/some_xml_file.xml'); 
echo '<pre>' . xmlpp($xml, true) . '</pre>'; 
?> 
+0

埃裏克漂亮的打印機適合我 – gray 2013-09-18 22:32:12