Convert form request data to xml in cakephp - php

I'm trying to convert all the form data in a cakephp request object to xml and then convert that to a string so that I can place it in a (blob) column in a mysql table.
I'm trying to do this current using the buildin xml builders in CakePHP 2.x.x as shown below but am getting an error.
if ($this->request->is('post')) {
$this->Survey->create();
$xml = Xml::build($this->request->data);
}
The form is shown below
<?php echo $this->Form->create('Survey'); ?>
<fieldset>
<legend><?php echo __('Add Survey'); ?></legend>
<?php
echo $this->Form->input('Question 1');
echo $this->Form->input('Question 2');
echo $this->Form->input('Question 3');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
The error I'm getting seems to be due to the DOCDocument->createElement(string,string) in the stacktrace. I've also used other methods including building it manually like so:
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$doc->loadHTML($this->request->data);
$data = $this->request->input('Xml::build',
array('return' => 'domdocument'));
while(list($key,$value) = each($this->request->data)){
$data = $data . $key . $value;
}
if(isset($this->request->data)){
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->appendChild($doc->createElement('survey'));
$post = $this->request->data['Survey'];
unset($post['submit']);
foreach($post as $key => $value){
$node = $doc->createElement($key,$value);
$root->appendChild($node);
}
$test1 = $doc->saveXML();
Any help would be appreciated. Thank you.

See the transforming an array into a string of XML section.

Related

I am trying to scrap website but get only one array detail in xml file

I am trying to scrape this webpage. In this webpage I have to get the job title and its location. Which I am able to get from my code. But the problem is coming that when I am sending it in XML, then only one detail is going from the array list.
I am using goutte CSS selector library and also please tell me how to scrap pagination in goutte CSS selector library.
here is my code:
$httpClient = new \Goutte\Client();
$response = $httpClient->request('GET', 'https://www.simplyhired.com/search?q=pharmacy+technician&l=American+Canyon%2C+CA&job=X5clbvspTaqzIHlgOPNXJARu8o4ejpaOtgTprLm2CpPuoeOFjioGdQ');
$job_posting_location = [];
$response->filter('.LeftPane article .SerpJob-jobCard.card .jobposting-subtitle span.JobPosting-labelWithIcon.jobposting-location span.jobposting-location')
->each(function ($node) use (&$job_posting_location) {
$job_posting_location[] = $node->text() . PHP_EOL;
});
$joblocation = 0;
$response->filter('.LeftPane article .SerpJob-jobCard.card .jobposting-title-container h3 a')
->each( function ($node) use ($job_posting_location, &$joblocation, $httpClient) {
$job_title = $node->text() . PHP_EOL; //job title
$job_posting_location = $job_posting_location[$joblocation]; //job posting location
// display the result
$items = "{$job_title} # {$job_posting_location}\n\n";
global $results;
$result = explode('#', $items);
$results['job_title'] = $result[0];
$results['job_posting_location'] = $result[1];
$joblocation++;
});
function convertToXML($results, &$xml_user_info){
foreach($results as $key => $value){
if(is_array($value)){
$subnode = $xml_user_info->addChild($key);
foreach ($value as $k=>$v) {
$xml_user_info->addChild("$k",htmlspecialchars("$v"));
}
}else{
$xml_user_info->addChild("$key",htmlspecialchars("$value"));
}
}
return $xml_user_info->asXML();
}
$xml_user_info = new SimpleXMLElement('<root/>');
$xml_content = convertToXML($results,$xml_user_info);
$xmlFile = 'details.xml';
$handle = fopen($xmlFile, 'w') or die('Unable to open the file: '.$xmlFile);
if(fwrite($handle, $xml_content)) {
echo 'Successfully written to an XML file.';
}
else{
echo 'Error in file generating';
}
what i got in xml file --
<?xml version="1.0"?>
<root><job_title>Pharmacy Technician
</job_title><job_posting_location> Vallejo, CA
</job_posting_location></root>
what i want in xml file --
<?xml version="1.0"?>
<root>
<job_title>Pharmacy Technician</job_title>
<job_posting_location> Vallejo, CA</job_posting_location>
<job_title>Pharmacy Technician 1</job_title>
<job_posting_location> Vallejo, CA</job_posting_location>
<job_title>Pharmacy Technician New</job_title>
<job_posting_location> Vallejo, CA</job_posting_location>
and so on...
</root>
You overwrite the values in the $results variable. You're would need to do something like this to append:
$results[] = [
'job_title' => $result[0];
'job_posting_location' => $result[1]
];
However here is no need to put the data into an array at all, just create the
XML directly with DOM.
Both your selectors share the same start. Iterate the card and then fetch
related data.
$httpClient = new \Goutte\Client();
$response = $httpClient->request('GET', $url);
$document = new DOMDocument();
// append document element node
$postings = $document->appendChild($document->createElement('jobs'));
// iterate job posting cards
$response->filter('.LeftPane article .SerpJob-jobCard.card')->each(
function($jobCard) use ($document, $postings) {
// fetch data
$location = $jobCard
->filter(
'.jobposting-subtitle span.JobPosting-labelWithIcon.jobposting-location span.jobposting-location'
)
->text();
$title = $jobCard->filter('.jobposting-title-container h3 a')->text();
// append 'job' node to group data in result
$job = $postings->appendChild($document->createElement('job'));
// append data nodes
$job->appendChild($document->createElement('job_title'))->textContent = $title;
$job->appendChild($document->createElement('job_posting_location'))->textContent = $location;
}
);
echo $document->saveXML();

Reading XML POST data from URL

I am working with a 3rd party SMS supplier which they are sending me the delivery report of the SMS via URL as below:
http://www.mydomain.com/dlr.php <DeliveryReport><message id="024042313063119191" sentdate="2014/04/23 15:06:31" donedate="2014/04/23 15:06:35" status="DELIVERED" gsmerror="0" price="7.0" /></DeliveryReport>
And i am trying to read the XML data in dlr.php like below:
<?php
// read raw POST data
$postData = file_get_contents("php://input");
$dom = new DOMDocument();
$dom->loadXML($postData);
// create new XPath object for quering XML elements (nodes)
$xPath = new domxpath($dom);
// query “message” element
$reports = $xPath->query("/DeliveryReport/message");
// write out attributes of each “message” element
foreach ($reports as $node) {
echo “<br>id: “ . $node->getAttribute('id');
echo “<br>sent: “ . $node->getAttribute('sentdate');
echo “<br>done: “ . $node->getAttribute('donedate');
echo “<br>status: “ . $node->getAttribute('status');
echo “<br>gsmerrorcode: “ . $node->getAttribute('gsmerrorcode');
}
?>
I am getting this error:
Warning: DOMDocument::loadXML(): Empty string supplied as input in dlr.php
Any help how can I read the posted data correctly.
Thanks,
You can simply use this function for getting data from XML
function getFeed($feed_url)
{
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
foreach($x->channel->item as $entry) : ?>
<?php
$pdate = $entry->pubDate;
$pdate = rtrim($pdate,' -500');
$pdate = explode(', ',$pdate);
?>
<div >
<a href="<?php echo $entry->link; ?>" target="_blank">
<span > <?php echo $entry->title;?></span></a> <?php echo $pdate[1]; ?>
</div>
<?php
endforeach;
}
getFeed("// Your URL");

PHP: How to find an element with particular name attribute in html (from url)

I am currently using PHP's file_get_contents($url) to fetch content from a URL. After getting the contents I need to inspect the given HTML chunk, find a 'select' that has a given name attribute, extract its options, and their values text. I am not sure how to go about this, I can use PHP's simplehtmldom class to parse html, but how do I get a particular 'select' with name 'union'
<span class="d3-box">
<select name='union' class="blockInput" >
<option value="">Select a option</option> ..
Page can have multiple 'select' boxes and hence I need to specifically look by name attribute
<?php
include_once("simple_html_dom.php");
$htmlContent = file_get_contents($url);
foreach($htmlContent->find(byname['union']) as $element)
echo 'option : value';
?>
Any sort of help is appreciated. Thank you in advance.
Try this PHP code:
<?php
require_once dirname(__FILE__) . "/simple_html_dom.php";
$url = "Your link here";
$htmlContent = str_get_html(file_get_contents($url));
foreach ($htmlContent->find("select[name='union'] option") as $element) {
$option = $element->plaintext;
$value = $element->getAttribute("value");
echo $option . ":" . $value . "<br>";
}
?>
how about this:
$htmlContent = file_get_html('your url');
$htmlContent->find('select[name= "union"]');
in object oriented way:
$html = new simple_html_dom();
$htmlContent = $html->load_file('your url');
$htmlContent->find('select[name= "union"]');
From DOMDocument documentation: http://www.php.net/manual/en/class.domdocument.php
$html = file_get_contents( $url );
$dom = new DOMDocument();
$dom->loadHTML( $html );
$selects = $dom->getElementsByTagName( 'select' );
$select = $selects->item(0);
// Assuming all children are options.
$children = $select->childNodes;
$options_values = array();
for ( $i = 0; $i < $children->length; $i++ )
{
$item = $children->item( $i );
$options_values[] = $item->nodeValue;
}

How can i get the value of attribute in of a xml node in php?

I'm using simplexml to read a xml file. So far i'm unable to get the attribute value i'm looking for. this is my code.
if(file_exists($xmlfile)){
$doc = new DOMDocument();
$doc->load($xmlfile);
$usergroup = $doc->getElementsByTagName( "preset" );
foreach($usergroup as $group){
$pname = $group->getElementsByTagName( "name" );
$att = 'code';
$name = $pname->attributes()->$att; //not working
$name = $pname->getAttribute('code'); //not working
if($name==$preset_name){
echo($name);
$group->parentNode->removeChild($group);
}
}
}
and my xml file looks like
<presets>
<preset>
<name code="default">Default</name>
<createdBy>named</createdBy>
<icons>somethignhere</icons>
</preset>
</presets>
Try this :
function getByPattern($pattern, $source)
{
$dom = new DOMDocument();
#$dom->loadHTML($source);
$xpath = new DOMXPath($dom);
$result = $xpath->evaluate($pattern);
return $result;
}
And you may use it like (using XPath) :
$data = getByPattern("/regions/testclass1/presets/preset",$xml);
UPDATE
Code :
<?php
$xmlstr = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><presets><preset><name code=\"default\">Default</name><createdBy>named</createdBy><icons>somethignhere</icons></preset></presets>";
$xml = new SimpleXMLElement($xmlstr);
$result = $xml->xpath("/presets/preset/name");
foreach($result[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
?>
Output :
code="default"
P.S. And also try accepting answers as #TJHeuvel mentioned; it's an indication that you respect the community (and the community will be more than happy to help you more, next time...)
Actually question in my head includes deleting a node as well , mistakenly i could not add it. So in my point of view this is the complete answer, i a case if someone else find this useful.
This answer doesn't include SimpleXMLElement class because how hard i tried it didn't delete the node with unset(); . So back to where i was , i finally found an answer. This is my code.
and its Simple!!!
if(file_exists($xmlfile)){
$doc = new DOMDocument();
$doc->load($xmlfile);
$presetgroup = $doc->getElementsByTagName( "preset" );
foreach($presetgroup as $group){
$pname = $group->getElementsByTagName( "name" );
$pcode = $pname->item(0)->getAttribute('code');
if($pcode==$preset_name){
echo($preset_name);
$group->parentNode->removeChild($group);
}
}
}
$doc->save($xmlfile);

parsing and comparing xml values using PHP XML DOM

I am trying to compare a node value and parse xml attribute values using PHP's DOM XML.
Below is what I have on my page but I am no longer get the results or an error.
PHP:
<?PHP
error_reporting(E_ALL);
ini_set("display_errors", 1);
//PRODUCT URL
$xml_url = "http://<servername>/services/info?storeId=2;
//LOCAL TEST URL
//$xml_url = "testXML.xml";
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml_url);
//THIS IS WHERE MY ISSUE IS (I THINK)
$errorCheck = $xmlDoc->getElementsByTagName( "testcode"" );
$errorValue = $errorCheck->item(0)->nodeValue;
if ($errorValue != "1"){
//loop and show data
$grads = $xmlDoc->getElementsByTagName( "$grads" );
foreach( $grads as $grad )
{
$students = $grad->getElementsByTagName( "student" );
$student = $students>item(0)->nodeValue;
$times = $grad->getElementsByTagName( "time" );
$time = $times->item(0)->nodeValue;
echo "<tr><td>".$student."</td><td>".$time."</td></tr>";
}
}else{
?>
<H1> Show an html message</H1>
<?
}
?>
THIS IS MY TEST XML:
<response>
<testcode>0</testcode>
<grad student="mike" time="10:00am"/>
<grad student="Bob" time="11:00am" />
<grad student="TOM" time="11:30am" />
<grad student="Greg" time="1:00pm" />
</response>

Categories