I want to append some text to divs which has same class.
$dom = new DOMdocument();
$dom->formatOutput = true;
#$dom->loadHTMLFile('first.html');
$xpath = new DOMXPath($dom)
$after = new DOMText('Newly appended text');
$elements = $xpath->query('//div[#class="mix"]');
foreach($elements as $element)
{
$element->appendChild($after);
//echo $dom->saveHTML();
}
$dom->saveHTMLFile('first.html');
But when I open first.html, The appended text is only appeded to last div of above class.
If I uncomment saveHTML() then it shows perfect result. Just problem after saving.
You cannot append the same DOM node to multiple points in the tree, which is what you are doing here. You need to create a separate (but identical) node each time:
foreach($elements as $element)
{
$after = new DOMText('Newly appended text'); // moved this inside the loop
$element->appendChild($after);
}
Related
I'm very new to php. I understand that echo is how you output text, but not sure how to apply it with the below scenario. Below, data is being scraped and outputted. Wondering if there's a way with the file_put_contents to add a text to the output, and the text I'm trying to add is a "%". Reason is the output of the below code is a random number that changes daily, and it's in fact a percent, so I'd like to add that to the end of the output every time.
Thanks so much for any assistance.
// get japanchange
function getJapanchange(){
$doc = new DOMDocument;
// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;
// Most HTML Developers are chimps and produce invalid markup...
$doc->strictErrorChecking = false;
$doc->recover = true;
$doc->loadHTMLFile('http://________________//global-
indices/');
$xpath = new DOMXPath($doc);
$query = "//div[#class='MT10']";
$entries = $xpath->query($query);
foreach ($entries as $entry) {
$result = trim($entry->textContent);
$ret_ = explode(' ', $result);
//make sure every element in the array don't start or end with blank
foreach ($ret_ as $key=>$val){
$ret_[$key]=trim($val);
}
//delete the empty element and the element is blank "\n" "\r" "\t"
//I modify this line
$ret_ = array_values(array_filter($ret_,deleteBlankInArray));
//echo the last element
file_put_contents(globalVars::$_cache_dir . "japanchange",
$ret_[56]);
}
}
If you just want to add a % to the end of the output to the file your already using. You could simple do
file_put_contents(globalVars::$_cache_dir . "japanchange",
$ret_[56].'%');
I'm trying add some data to an existing XML file using PHP's SimpleXML. The problem is it adds all the data in a single line:
<name>blah</name><class>blah</class><area>blah</area> ...
And so on. All in a single line. How to introduce line breaks?
How do I make it like this?
<name>blah</name>
<class>blah</class>
<area>blah</area>
I am using asXML() function.
Thanks.
You could use the DOMDocument class to reformat your code:
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();
Gumbo's solution does the trick. You can do work with simpleXml above and then add this at the end to echo and/or save it with formatting.
Code below echos it and saves it to a file (see comments in code and remove whatever you don't want):
//Format XML to save indented tree rather than one line
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
//Echo XML - remove this and following line if echo not desired
echo $dom->saveXML();
//Save XML to file - remove this and following line if save not desired
$dom->save('fileName.xml');
Use dom_import_simplexml to convert to a DomElement. Then use its capacity to format output.
$dom = dom_import_simplexml($simple_xml)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
As Gumbo and Witman answered; loading and saving an XML document from an existing file (we're a lot of newbies around here) with DOMDocument::load and DOMDocument::save.
<?php
$xmlFile = 'filename.xml';
if( !file_exists($xmlFile) ) die('Missing file: ' . $xmlFile);
else
{
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dl = #$dom->load($xmlFile); // remove error control operator (#) to print any error message generated while loading.
if ( !$dl ) die('Error while parsing the document: ' . $xmlFile);
echo $dom->save($xmlFile);
}
?>
Looking to add to my DOM code to include targeting the last image of my wordpress posts
EDIT - the code I have only targets/pulls out the blockquote of the content. I want to be able to use the last image in my wordpress post as a background for specific div.
html
<?php
$content = get_the_content();
$content = wpautop($content);
$doc = new DOMDocument();
$doc->loadHTML(get_the_content(), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//blockquote') as $node) {
$node->parentNode->removeChild($node);
}
// My attempt
foreach ($xpath->query('//img') as $node) {
$node->parentNode->removeChild($node);
}
$content = $doc->saveHTML($doc);
?>
My attempt has been able to remove the images altogether not target the last one.
Try preg_match_all():
// Make sure shortcodes are fetched.
$content = apply_filters('the_content', $content);
preg_match_all('/<img([^>]+)>/', $content, $images);
$last_image = array_pop($images[0]);
I'm trying add some data to an existing XML file using PHP's SimpleXML. The problem is it adds all the data in a single line:
<name>blah</name><class>blah</class><area>blah</area> ...
And so on. All in a single line. How to introduce line breaks?
How do I make it like this?
<name>blah</name>
<class>blah</class>
<area>blah</area>
I am using asXML() function.
Thanks.
You could use the DOMDocument class to reformat your code:
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();
Gumbo's solution does the trick. You can do work with simpleXml above and then add this at the end to echo and/or save it with formatting.
Code below echos it and saves it to a file (see comments in code and remove whatever you don't want):
//Format XML to save indented tree rather than one line
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
//Echo XML - remove this and following line if echo not desired
echo $dom->saveXML();
//Save XML to file - remove this and following line if save not desired
$dom->save('fileName.xml');
Use dom_import_simplexml to convert to a DomElement. Then use its capacity to format output.
$dom = dom_import_simplexml($simple_xml)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
As Gumbo and Witman answered; loading and saving an XML document from an existing file (we're a lot of newbies around here) with DOMDocument::load and DOMDocument::save.
<?php
$xmlFile = 'filename.xml';
if( !file_exists($xmlFile) ) die('Missing file: ' . $xmlFile);
else
{
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dl = #$dom->load($xmlFile); // remove error control operator (#) to print any error message generated while loading.
if ( !$dl ) die('Error while parsing the document: ' . $xmlFile);
echo $dom->save($xmlFile);
}
?>
I'm creating a tool that works with file strings and I need to get the line number where a node is found. It is, I have this:
$dom = new DOMDocument('1.0');
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//text()") as $q) {
// $line = WHAT???
$strings[trim($q->nodeValue)] = $line;
}
and I need to know in which line begins the string I'm storing in $strings array. Is it possible to get it?
Each DOMNode object has a getLineNo() function that returns this. In your case it's a DOMText object that extends from DOMNode:
foreach ($xpath->query("//text()") as $q) {
$line = $q->getLineNo();
$strings[trim($q->nodeValue)] = $line;
}
You might need to upgrade to PHP 5.3 if you have not yet to make use of that function.