0

这是我的 PHP 代码,用于使用 SimpleXML 和 DOM 从 URL 读取 XML 以更改一些参数并将其显示在网页上

我正在阅读的提要位于http://tinyurl.com/boy7mr5

<?php

  $xml = simplexml_load_file('http://www.abc.com');


  $doc = new DOMDocument();
  $doc->formatOutput = true;

  $r = $doc->createElement( "All_Products" );
  $doc->appendChild( $r );

  foreach( $xml as $Product)
  {


 $b = $doc->createElement( "Product" );
   $doc->appendChild( $b );

  foreach($Product as $prname=>$value)
  {


  $prname1  = $doc->createElement( $prname );
  $prname1->appendChild(
  $doc->createTextNode( $value )
  );
  $b->appendChild($prname1);
  if($prname=='ProductName')
  {

  $ProductURL = $doc->createElement( "ProductURL" );
  $ProductURL->appendChild(
  $doc->createTextNode('http://www.abc.com/'.$Product->ProductName.'-p/'.$Product->ProductCode .'.htm' )
  );
  $b->appendChild( $ProductURL );

  }
  if($prname=='Categories'){

foreach($value as $catname=>$catvalue)
  {
   $c = $doc->createElement( "Category" );
   $doc->appendChild( $c );
  foreach($catvalue as $catname1=>$catvalue1)
  {
 // echo $catname1."==".$catvalue1;
    $catname12 = $doc->createElement( $catname1);
  $catname12 ->appendChild(
  $doc->createTextNode(htmlspecialchars_decode($catvalue1) )
  );
  $c->appendChild( $catname12);

  }
   $prname1->appendChild( $c );
  }
  }


  }
  $r->appendChild( $b );

  }
  echo $doc->saveXML();

  ?>

最后一行按原样打印所有 XML,但它显示了垃圾数据,如您在此 URL http://tinyurl.com/bty8286中看到的那样。

我希望数据在浏览器中看起来像这样http://tinyurl.com/boy7mr5,我应该在代码中更改什么

4

1 回答 1

2

It's a matter of the Content-Type HTTP header. The second link uses the application/xml while the first one uses php's default text/html. You can change your php script's HTTP headers with the header() function.

header('content-type: application/xml');

EDIT:

I've been able to fetch the original input, the only the header doesn't made it work (at least in firefox), got parse error on line 48580, this is due no encoding was set to the DOMDocument object, while the original input is in utf-8. With

$doc = new DOMDocument('1.0', 'utf-8');

should work.

于 2012-07-22T17:28:39.617 回答