2012-05-04 1 views
0

Я просто хочу добавить cdata в XML-узел - описание. Моя функция xml приведена ниже. Я попытался с помощью биты следующей функции на php.net в моей функцииНевозможно добавить CDATA в мою XML-строку с помощью simplexml с php

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

current xml document tree, just want to a cdata in the description tags

+0

Я пробовал бит в нем, который говорит создать CDATASection, который я адаптировал из этой функции с php.net. Я не получаю никаких ошибок, просто ничего не добавляет к моему XML-документу. – Nicola

+0

Я не уверен, что simpleXML поддерживает эту функциональность. Как следует из названия, это простое манипулирование XML. Возможно, вам придется прибегать к полным классам DOM. – GordonM

+0

О, ладно спасибо, я не уверен, как это сделать, поэтому мне, возможно, придется оставить его – Nicola

ответ

1

Попробуйте это для размера. Дайте мне знать, если у вас с этим возникли проблемы/вопросы об этом (FIXED).

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

} 

N.B. это теперь выдает исключение, если DOMDocument::load() терпит неудачу - не забудьте сделать catch!

+0

спасибо, что работа, потрясающая! – Nicola

Смежные вопросы