I'm writing a script that adds nodes to an xml file. In addition to this I have an external dtd I made to handle the organization to the file. However the script I wrote keeps overwriting the dtd in the empty xml file when it's done appending nodes. How can I stop this from happening?
Code:
<?php
/*Dom vars*/
$dom = new DOMDocument("1.0", "UTF-8");
$previous_value = libxml_use_internal_errors(TRUE);
$dom->load('post.xml');
libxml_clear_errors();
libxml_use_internal_errors($previous_value);
$dom->formatOutput = true;
$entry = $dom->getElementsByTagName('entry');
$date = $dom->getElementsByTagName('date');
$para = $dom->getElementsByTagname('para');
$link = $dom->getElementsByTagName('link');
/* Dem POST vars used by dat Ajax mah ziggen, yeah boi*/
if (isset($_POST['Text'])){
$text = trim($_POST['Text']);
}
/*
function post(){
global $dom, $entry, $date, $para, $link,
$home, $about, $contact, $text;
*/
$entryC = $dom->createElement('entry');
$dateC = $dom->createElement('date', date("m d, y H:i:s")) ;
$entryC->appendChild($dateC);
$tab = "\n";
$frags = explode($tab, $text);
$i = count($frags);
$b = 0;
while($b < $i){
$paraC = $dom->createElement('para', $frags[$b]);
$entryC->appendChild($paraC);
$b++;
}
$linkC = $dom->createElement('link', rand(100000, 999999));
$entryC->appendChild($linkC);
$dom->appendChild($entryC);
$dom->save('post.xml');
/*}
post();
*/echo 1;
?>
It looks like in order to do this, you'd have to create a DOMDocumentType using
DOMImplementation::createDocumentType
then create an empty document using the DOMImplementation, and pass in the DOMDocumentType you just created, then import the document you loaded. This post: http://pointbeing.net/weblog/2009/03/adding-a-doctype-declaration-to-a-domdocument-in-php.html and the comments looked useful.
I'm guessing this is happening because after parsing/validation, the DTD isn't part of the DOM anymore, and PHP therefore isn't able to include it when the document is serialized.
Do you have to use a DTD? XML Schemas can be linked via attributes (and the link is therefore part of the DOM). Or there's RelaxNG, which can be linked via a processing instruction. DTDs have all this baggage that comes with them as a holdover from SGML. There are better alternatives.
Related
I am trying to add multiple elements, within a parent element with PHP (XML):
This is what I am trying to achieve:
<ns0:XmlInterchange xmlns:ns0="http://www.edi.com.au/EnterpriseService/" xmlns:ext="http://esb.dsv.com/ExtensionFunctions">
<ns0:InterchangeInfo>
<ns0:Date>2017-07-20 13:41:48</ns0:Date>
<ns0:XmlType>Verbose</ns0:XmlType>
<ns0:Source>
<ns0:EnterpriseCode>Company</ns0:Enterprisecode>
</ns0:Source>
</ns0:InterchangeInfo>
</ns0:XmlInterchange>
I have below PHP code:
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->formatOutput = true;
$interchange = $xml->createElementNS('ns0', 'ns0:XmlInterchange');
$interchange->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ns0', 'http://www.edi.com.au/EnterpriseService/');
$interchange->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ext', 'http://esb.dsv.com/ExtensionFunctions');
$xml->appendChild($interchange); //Add above attributes to our element. <!Xmlinterchange->
$item = $xml->createElement('ns0:InterchangeInfo');
$item->appendChild($xml->createElement('ns0:Date',$invoice_date));
$item->appendChild($xml->createElement('ns0:XmlType','Verbose'));
$item = $xml->createElement('ns0:Source');
$item->appendChild($xml->createElement('ns0:EnterpriseCode','Company'));
$interchange->appendChild($item);
unset($item); //Reset $item, so we can use the variable again.
However, above outputs:
<ns0:XmlInterchange xmlns:ns0="http://www.edi.com.au/EnterpriseService/" xmlns:ext="http://esb.dsv.com/ExtensionFunctions">
<ns0:Source>
<ns0:EnterpriseCode>Company</ns0:EnterpriseCode>
</ns0:Source>
</ns0:XmlInterchange>
I want to be able to get the <ns0:Source> element to be within the <ns0:InterChangeInfo> element, but together with the other elements.
You have to append the <ns0:Source> to the <ns0:InterchangeInfo>. After that append the <ns0:InterchangeInfo> to <ns0:XmlInterchange>.
Remember: ->appendChild() means not append to but append inside. So $a->appendChild($b); means you append b inside a.
Try:
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->formatOutput = true;
$interchange = $xml->createElementNS('ns0', 'ns0:XmlInterchange');
$interchange->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ns0', 'http://www.edi.com.au/EnterpriseService/');
$interchange->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ext', 'http://esb.dsv.com/ExtensionFunctions');
$item = $xml->createElement('ns0:InterchangeInfo');
$item->appendChild($xml->createElement('ns0:Date',$invoice_date));
$item->appendChild($xml->createElement('ns0:XmlType','Verbose'));
$source = $xml->createElement('ns0:Source');
$source->appendChild($xml->createElement('ns0:EnterpriseCode','Company'));
$item->appendChild($source);
$interchange->appendChild($item);
$xml->appendChild($interchange);
I had this line of code which was working fine until I update the php version of my server from 5.3 to 5.6.
It re-writes a xml file.
I guess this line is not compactible with 5.6, but I don't know what is wrong exactly:
$newXml->asXml('my_xml.xml');
And this is the error message:
Fatal error: Call to a member function asXml() on boolean in /usr/home/example/www/sites/all/modules/custom/inmovilla_rewrite/inmovilla_rewrite.module on line 71
What changes should I do here?
UPDATE Complete function
<?php
/**
* Implemetns hook_cron()
*/
function inmovilla_rewrite_cron() {
$xml_external_path = 'http://ap.apinmo.com/portal/mls/jamp623433/my_xml.xml';
$xml = file_get_contents($xml_external_path);
$pattern = '/<unico>(.*?)<\/unico>/';
$response = preg_replace_callback($pattern,function($match){
$valueUnico = trim($match[1]);
$valueUnico = substr($valueUnico, 0, -4);
return '<unico>'.$valueUnico.'</unico>';
},$xml);
$searches = array();
$replacements = array();
for ($i = 1; $i <= 30; $i++) {
$searches[] = 'foto'.$i.'>';
$replacements[] = 'foto1>';
}
$response = str_replace( $searches, $replacements, $response ) ;
$newXml = $response;
$newXml = simplexml_load_string( $newXml );
$newXml->asXml('my_xml.xml');
}
You are calling the method: asXml() on a boolean data-type, not an instance of SimpleXMLElement - you are presumably not feeding in a "well-formed" XML string.
See here: http://php.net/manual/en/function.simplexml-load-string.php
Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, or FALSE on failure.
You should firstly implement some error checking rather than assume that you have a SimpleXMLElement instance, e.g.
$newXml = simplexml_load_string($newXml);
if ($newXml instanceof SimpleXMLElement) {
$xml = $newXml->asXml('my_xml.xml');
}
However, you will need to do some further debugging on the values held in $newXml / $response to see what is wrong with the XML string. I cannot see the XML contents in your question to advise any further as to why the change of PHP version has affected this.
I have a several problems to moment to create a WSDL with REST in PHP. I read a little bit about this, supposedly REST use WADL. I need a library or framework that generated a WADL or type WSDL of my code PHP (class, methods, vars).
Thanks a lot!
I created a simulation with php but this no get the return vars
... Class
... Methods
... Vars
if(isset($_GET['wadl'])):
header('Content-Type: text/xml');
$foo = new proveedores();
$get_class = get_class($foo);
// create the new XML document
$dom = new DOMDocument('1.0', 'iso-8859-1');
// create the root element
$list_of_teams = $dom->createElement($get_class);
$dom->appendChild($list_of_teams);
$class = new ReflectionClass($get_class);
$methods = $class->getMethods();
foreach ($methods as $m) {
$method = $class->getMethod($m->name);
// create the first element
$team = $dom->createElement($m->name);
$list_of_teams->appendChild($team);
$parameters = $method -> getParameters();
if(!empty($parameters)):
foreach ($parameters as $p) {
$name = $team->appendChild($dom->createElement('parameters'));
$name->appendChild($dom->createTextNode($p -> name));
}
endif;
}
print $xml_result = $dom->saveXML();
endif;
I am trying to read a website's content but i have a problem i want to get images, links these elements but i want to get elements them selves not the element content for instance i want to get that: i want to get that entire element.
How can i do this..
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.link.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$dom = new DOMDocument;
#$dom->loadHTML($output);
$items = $dom->getElementsByTagName('a');
for($i = 0; $i < $items->length; $i++) {
echo $items->item($i)->nodeValue . "<br />";
}
curl_close($ch);;
?>
You appear to be asking for the serialized html of a DOMElement? E.g. you want a string containing link text? (Please make your question clearer.)
$url = 'http://example.com';
$dom = new DOMDocument();
$dom->loadHTMLFile($url);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $a) {
// Best solution, but only works with PHP >= 5.3.6
$htmlstring = $dom->saveHTML($a);
// Otherwise you need to serialize to XML and then fix the self-closing elements
$htmlstring = saveHTMLFragment($a);
echo $htmlstring, "\n";
}
function saveHTMLFragment(DOMElement $e) {
$selfclosingelements = array('></area>', '></base>', '></basefont>',
'></br>', '></col>', '></frame>', '></hr>', '></img>', '></input>',
'></isindex>', '></link>', '></meta>', '></param>', '></source>',
);
// This is not 100% reliable because it may output namespace declarations.
// But otherwise it is extra-paranoid to work down to at least PHP 5.1
$html = $e->ownerDocument->saveXML($e, LIBXML_NOEMPTYTAG);
// in case any empty elements are expanded, collapse them again:
$html = str_ireplace($selfclosingelements, '>', $html);
return $html;
}
However, note that what you are doing is dangerous because it could potentially mix encodings. It is better to have your output as another DOMDocument and use importNode() to copy the nodes you want. Alternatively, use an XSL stylesheet.
I'm assuming you just copy-pasted some example code and didn't bother trying to learn how it actually works...
Anyway, the ->nodeValue part takes the element and returns the text content (because the element has a single text node child - if it had anything else, I don't know what nodeValue would give).
So, just remove the ->nodeValue and you have your element.
I have write this little class below which generates a XML sitemap although when I try to add this to Google Webmaster I get error:
Sitemap URL: http://www.moto-trek.co.uk/sitemap/xml
Unsupported file format
Your Sitemap does not appear to be in a supported format. Please ensure it meets our Sitemap guidelines and resubmit.
<?php
class Frontend_Sitemap_Xml extends Cms_Controller {
/**
* Intercept special function actions and dispatch them.
*/
public function postDispatch() {
$db = Cms_Db_Connections::getInstance()->getConnection();
$oFront = $this->getFrontController();
$oUrl = Cms_Url::getInstance();
$oCore = Cms_Core::getInstance();
$absoDomPath = $oFront->getDomain() . $oFront->getHome();
$pDom = new DOMDocument();
$pXML = $pDom->createElement('xml');
$pXML->setAttribute('version', '1.0');
$pXML->setAttribute('encoding', 'UTF-8');
// Finally we append the attribute to the XML tree using appendChild
$pDom->appendChild($pXML);
$pUrlset = $pDom->createElement('urlset');
$pUrlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
$pXML->appendChild($pUrlset);
// FETCH content and section items
$array = $this->getDataset("sitemap")->toArray();
foreach($array["sitemap"]['rows'] as $row) {
try {
$content_id = $row['id']['fvalue'];
$url = "http://".$absoDomPath.$oUrl->forContent($content_id);
$pUrl = $pDom->createElement('url');
$pLoc = $pDom->createElement('loc', $url);
$pLastmod = $pDom->createElement('lastmod', gmdate('Y-m-d\TH:i:s', strtotime($row['modified']['value'])));
$pChangefreq = $pDom->createElement('changefreq', ($row['changefreq']['fvalue'] != "")?$row['changefreq']['fvalue']:'monthly');
$pPriority = $pDom->createElement('priority', ($row['priority']['fvalue'])?$row['priority']['fvalue']:'0.5');
$pUrl->appendChild($pLoc);
$pUrl->appendChild($pLastmod);
$pUrl->appendChild($pChangefreq);
$pUrl->appendChild($pPriority);
$pUrlset->appendChild($pUrl);
} catch(Exception $e) {
throw($e);
}
}
// Set content type to XML, thus forcing the browser to render is as XML
header('Content-type: text/xml');
// Here we simply dump the XML tree to a string and output it to the browser
// We could use one of the other save methods to save the tree as a HTML string
// XML file or HTML file.
echo $pDom->saveXML();
}
}
?>
urlset should by root element, but in your case it is xml. So appending urlset directly into domdocument should solve your problem.
$pDom = new DOMDocument('1.0','UTF-8');
$pUrlset = $pDom->createElement('urlset');
$pUrlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
foreach( ){ }
$pDom->appendChild($pUrlset);
echo $pDom->saveXML();