0

我只是想将 cdata 添加到 xml 节点 - 描述。我的xml函数如下。我尝试在我的函数中使用php.net上的以下函数

<?php
function updateXMLFile($itemName, $description, $pageName, $imageFileName)
{
  $imageSrc         = "<img src='http://nicolaelvin.com/authoring/phpThumb/phpThumb.php?src=../images/" . $imageFileName . "&w=100'/>";
  $id               = strtolower($id = str_replace(' ', '_', $itemName));
  $directLinkToItem = 'http://nicolaelvin.com/authoring/' . $pageName . '.php#' . $id;

  $xml  = simplexml_load_file('nicolaElvinsPortfolio.xml');
  $item = $xml->channel->addChild('item');
  $item->addChild('title', $itemName);

  $item->addChild('pubDate', date('r'));
  $item->addChild('link', $directLinkToItem);
  $item->addChild('description');
  $cdata->description->createCDATASection('testyfhgjhsgsdjahgs');
  $item->appendChild($cdata);

  ///Format XML to save indented tree rather than one line
  $dom                     = new DOMDocument('1.0');
  $dom->preserveWhiteSpace = false;
  $dom->formatOutput       = true;
  $dom->loadXML($xml->asXML());

  //Save XML to file - remove this and following line if save not desired
  $dom->save('nicolaElvinsPortfolio.xml');

}

//function from php.net
function sxml_cdata($path, $string)
{
  $dom   = dom_import_simplexml($path);
  $cdata = $dom->ownerDocument->createCDATASection($string);
  $dom->appendChild($cdata);
}
?>

当前的xml文档树,只想到一个cdata里面的description标签

4

1 回答 1

1

试穿这个尺寸。如果您对此有任何问题/对此有任何疑问,请告诉我(已修复)。

function updateXMLFile($itemName, $description, $pageName, $imageFileName) {

  // Path to file that will be used
  $filePath = 'nicolaElvinsPortfolio.xml';

  // Create links - don't forget to escape values appropriately with urlencode(), htmlspecialchars() etc
  $imageSrc = "<img src='".htmlspecialchars('http://nicolaelvin.com/authoring/phpThumb/phpThumb.php?src=../images/'.urlencode($imageFileName).'&w=100')."'/>";
  $directLinkToItem = 'http://nicolaelvin.com/authoring/'.urlencode($pageName).'.php#'.urlencode(strtolower(str_replace(' ', '_', $itemName)));

  // Create the CDATA value - whatever you want this to look like
  $cdata = "$description: $imageSrc";

  // Create a DOMDocument
  $dom = new DOMDocument('1.0');
  $dom->preserveWhiteSpace = false;
  $dom->formatOutput = true;

  // Load data from file into DOMDocument
  if (!$dom->load($filePath)) throw new Exception("Unable to load data source file '$filePath'");

  // Create the new <item> and add it to the document
  $item = $dom->getElementsByTagName('channel')->item(0)->appendChild(new DOMElement('item'));

  // Add the <item>'s sub elements
  $item->appendChild(new DOMElement('title', $itemName));
  $item->appendChild(new DOMElement('pubDate', date('r')));
  $item->appendChild(new DOMElement('link', $directLinkToItem));

  // Add the CDATA
  $item->appendChild(new DOMElement('description'))->appendChild(new DOMCdataSection($cdata));

  // Now save back to file
  $dom->save($filePath);

}

注意,如果失败,现在会抛出异常DOMDocument::load()- 不要忘记catch它!

于 2012-05-04T10:43:40.223 回答