Adding child nodes using SimpleXML - php

I have an XML document and want to insert a new node at a specific spot using SimpleXML.
The original XML is this:
<epp
xmlns="urn:ietf:params:xml:ns:epp-1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd"
>
<command>
<create>
<domain:create
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0"
xsi:schemaLocation="urn:ietf:params:xml:ns:domain-1.0 domain-1.0.xsd"
>
<domain:period unit="y"></domain:period>
</domain:create>
</create>
</command>
</epp>
after <domain:create> I need to add the following node:
<domain:ns>
<domain:hostAttr>
<domain:hostName></domain:hostName>
<domain:hostAddr ip="v4"></domain:hostAddr>
</domain:hostAttr>
</domain:ns>
How can I do that? I have tried this:
$xmlObj = simplexml_load_file('myXMLFile.xml');
$nsNode = $xmlObj->command->create->children(self::OBJ_URI_DOMAIN)->create->addChild('domain:ns');
$hostAttr = $nsNode->addChild('domain:hostAttr');
$hostName = $hostAttr->addChild('domain:hostName');
$hostAddr = $hostAttr->addChild('domain:hostAddr');
$hostAddr->addAtribute('ip', 'v4');
On this first line, I'm getting this warning:
Warning: SimpleXMLElement::addChild()
[simplexmlelement.addchild]: Cannot
add child. Parent is not a permanent
member of the XML tree
On the second line, and because of this, I'm getting:
Fatal error: Call to a member function
addChild() on a non-object
Thanks in advance.
Additional notes:
- The php version is higher then 5.1;
- I have successfully added child nodes later on this same XML.

I cannot reproduce the first error
<?php
echo phpversion(), "\n";
// $xmlObj = simplexml_load_file('myXMLFile.xml');
$xmlObj = getDoc();
$nsNode = $xmlObj->command->create->children('urn:ietf:params:xml:ns:domain-1.0')->create->addChild('domain:ns');
$nsNode->addChild('foo', 'Mary had a little lamb...');
echo $xmlObj->asxml();
function getDoc() {
return new SimpleXMLElement('<epp
xmlns="urn:ietf:params:xml:ns:epp-1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd"
>
<command>
<create>
<domain:create
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0"
xsi:schemaLocation="urn:ietf:params:xml:ns:domain-1.0 domain-1.0.xsd"
>
<domain:period unit="y"></domain:period>
</domain:create>
</create>
</command>
</epp>');
}
prints
5.3.2
<?xml version="1.0"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd">
<command>
<create>
<domain:create xmlns:domain="urn:ietf:params:xml:ns:domain-1.0" xsi:schemaLocation="urn:ietf:params:xml:ns:domain-1.0 domain-1.0.xsd">
<domain:period unit="y"/>
<domain:ns><domain:foo>Mary had a little lamb...</domain:foo></domain:ns></domain:create>
</create>
</command>
</epp>

You want the child added to <create>.
$nsNode = $xmlObj->command->create->addChild('domain:ns');
The children() method returns a filtered list of child nodes. This list is - just as the error message indicates - not a permanent member of the document tree, it cannot be added to.
Adding a child works on the respective parent element only, or the operation would not be called "addChild", but "addSibling" - and this is not how the concept of the DOM works.
PS: Your second error message ("Call to a member function on a non-object") is the result of regular sloppiness. You can't just use an object without checking that it is actually there, your code lacks this check:
if ($nsNode !== null) {
$hostAttr = $nsNode->addChild('domain:hostAttr');
$hostName = $hostAttr->addChild('domain:hostName');
$hostAddr = $hostAttr->addChild('domain:hostAddr');
$hostAddr->addAttribute('ip', 'v4');
} else {
echo "Oops, addChild() failed!";
}

Related

Simple XML Call to a member function addChild() on boolean

I have a problem composing XML sitemap using simple xml PHP function, having almost equal situation and when sitemap tag, it is not working:
$xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');
$sitemap = $xml->addChild("sitemap");
$sitemap->addChild("loc", "http://www.example.com/sitemap-1.xml");
Fatal error: Call to a member function addChild() on boolean
This is working reliably:
$xml = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');
$url = $xml->addChild("url");
$url->addChild("loc", "http://www.example.com/sitemap-2.xml");
Your issue is caused by simple mistake.
(you have - maybe forgot to change - closing tag from urlset to sitemapindex):
$xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');
Correct:
$xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></sitemapindex>');

PHP - Parse, Read XML

Not too sure what I'm doing wrong with parsing/reading an xml document.
My guess is that it's not standardized, and I'm going to need a different process to read anything from the string.
If that's the case, then I'm rather excited to learn how someone would read the xml.
Here's what I've got, and what I'm doing.
example.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="someurl.php"?>
<response>
<status>Error</status>
<error>The error message I need to extract, if the status says Error</error>
</response>
read_xml.php
<?php
$content = 'example.xml';
$string = file_get_contents($content);
$xml = simplexml_load_string($string);
print_r($xml);
?>
I'm getting no result back from the print_r.
I switched the xml to something more standard, like:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
...and it worked fine. So I'm sure it's due to a non-standard format, passed back from the source I'm getting it from.
How would I extract the <status> and <error> tags?
Tek has a good answer, but if you want to use SimpleXML, you can try something like this:
<?php
$xml = simplexml_load_file('example.xml');
echo $xml->asXML(); // this will print the whole string
echo $xml->status; // print status
echo $xml->error; // print error
?>
EDIT: If you have multiple <status> and <error> tags in your XML, have a look at this:
$xml = simplexml_load_file('example.xml');
foreach($xml->status as $status){
echo $status;
}
foreach($xml->error as $error){
echo $error;
}
I'm assuming <response> is your root. If it isn't, try $xml->response->status and $xml->response->error.
I prefer to use PHP's DOMDocument class better.
Try something like this:
<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="someurl.php"?>
<response>
<status>Error</status>
<error>The error message I need to extract, if the status says Error</error>
</response>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$statuses = $dom->getElementsByTagName('status');
foreach ($statuses as $status) {
echo "The status tag says: " . $status->nodeValue, PHP_EOL;
}
?>
Demo: http://codepad.viper-7.com/mID6Hp

PHP XML Remove Parent

XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<pages>
<page><title>Home</title><content>Lorem Ipsum</content></page>
<page><title>Pictures</title><content>Lorem Ipsum</content></page>
<page><title>Information</title><content>Lorem Ipsum</content></page>
</pages>
<css>
<css-tag><title>background-color</title><value>#FFF</value></css-tag>
</css>
<layout>1</layout>
</root>
PHP:
$title = $_GET['0'];
$xml = new DOMDocument('1.0', 'ISO-8859-1');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = true;
$xml->load($location);
$pages = $xml->getElementsByTagName("page");
foreach($pages as $page){
$pagetitle = $page->getElementsByTagName("title");
$pagetitlevalue = $pagetitle->item(0)->nodeValue;
if($title == $pagetitlevalue){
$pagetitle->item(0)->parentNode->removeChild($pagetitle->item(0));
}
}
$xml->save($location);
This code gets rid of just the <Title> node, how can it be changed to get rid of the parent <Page> node?
I can't figure out how to do this, I just manage to get rid of the title node and get loads of error codes
Whilst this is something I'd probably use xpath for, you can find...
$pagetitle->item(0)->parentNode->removeChild($pagetitle->item(0));
and replace with...
$pagetitle->item(0)->parentNode->parentNode->removeChild($pagetitle->item(0)->parentNode);
to go one level higher in your XML tree

Empty xml object when using SimpleXML - Node no longer exists

The xml is as follows:
<root>
<organizations>
<organization>
<info>
<orgID>1234</orgID>
<orgName>XYZ Company</orgName>
<address>
<address1>1 Main Street</address1>
<city>Somewhere</city>
<state>MI</state>
<zip>12334</zip>
</address>
</info>
</organization>
</organizations>
</root>
The code is as follows:
$ind = strpos($xmlResponse, "<");
$xml = simplexml_load_string(substr($xmlResponse, $ind));
//echo $xml;
$orgList = $xml->organizations->children();
foreach($orgList as $orgList)
{
echo $orgList->orgName;
}
And I get the following error:
Warning: main() [function.main]: Node no longer exists in...
The offending line is
foreach($orgList as $orgList)
Can anyone tell me what I'm doing wrong? I've tried accessing the xml through 50 different ways and either get that error or an empty xml object.
Thanks in advance!
It looks like you're overwriting the xml object when you loop with $orgList as $orgList. Try this instead:
foreach($orgList as $org)
echo $org->orgName;
Try the following:
$xml = simplexml_load_string($xml);
$org = $xml->organizations->children();
foreach($org as $k => $v)
{
echo $v->info->orgName;
}
Try using xpath
Put the XML in x.xml file
then create php file:
<?php
$xml = simplexml_load_file('x.xml');
$orgList = $xml->xpath("/root/organizations/organization/info");
print $orgList[0]->orgName;
?>

get Contents of the child tag using simeplxml_load_string in php

I have this XML
<parent>
<sms>
<response>
<message>message</message>
<reponse>text<response>
</response>
</sms>
<sms>
<response>
<message>message</message>
<reponse>text2<response>
</response>
</sms>
</parent>
I want to get the whole contents of response tag i.e <reponse1>text<response1> , <reponse2>text<response2> .which i will strore in an array. what i tried id
function xmlSplitUpResponseXML($xmlvalue)
{
$returnSplit = array();
$r = 0;
if(simplexml_load_string($xmlvalue))
{
$xml = simplexml_load_string($xmlvalue);
foreach($xml->children() as $child)
{
if(strtolower($child->getName())=='sms')
{
foreach ($child as $fields):
if(strtolower($fields->getName())=='response')
{
echo $fields;
}
}
} }
}
But the text is not echoed.
how can i do this.
Your XML isn't completly correct, but when fixed - try this:
echo $fields->message."<br>";
echo $fields->response."<hr>";
Works on your given example, with this fixed xml:
$string = "<parent><sms><response><message>message</message><response>text</response></response></sms><sms><response><message>message</message><response>text2</response></response></sms></parent>";
Hmm, seems like you need some XPath to the rescue...
Given the following fixed-up XML (note nested response nodes)
<parent>
<sms>
<response>
<message>message</message>
<response>text</response>
</response>
</sms>
<sms>
<response>
<message>message</message>
<response>text2</response>
</response>
</sms>
</parent>
The following PHP will do it for you.
<?php
$xml = simplexml_load_file( "sms.xml" );
// Find the sms response (note responses are nested in a parent response for some reason
$result = $xml->xpath('/parent/sms/response/response');
while(list( , $node) = each($result)) {
// to just output the value of the node
// echo $node;
// to wrap value in tags *bad idea*
echo $node->asXML();
}
?>
Not sure why you'd want to return an XML string, seems like a bad idea to me. What are you
doing with the output? Probably better to construct an XML document properly, just guessing...

Categories