Все вопросы: [domdocument]
27 вопросов
Как мне создать XML-файл с помощью php и запросить его загрузку?
Я использую domdocument для создания XML-файла: $dom = new DOMDocument('1.0', 'iso-8859-1'); echo $dom->saveXML(); Когда я нажимаю ссылку на этот файл, он просто отображает его как файл xml.Как мне предложить скачать вместо этого?Кроме того, как я могу предложить загрузить его как «bac...
PHP DomDocument Сохранить XML с помощью HTML
Как мне сохранить XML-файл, открытый с помощью DomDocument, чтобы HTML-код внутри не кодировался в HTML-объекты?
php DomDocument, требуется только первый элемент
Здравствуйте, я использовал DOMDocs в прошлом, но не знаю, как это сделать. $xmldoc = new DOMDocument(); $xmldoc->load('http://example.com'); $feeditem = $xmldoc->getElementsByTagName('data'); Мне нужен только первый экземпляр тега data.Обычно я бы написал цикл foreach: foreach($f...
PHP DOMDocument getting Attribute of Tag
Hello I have an api response in xml format with a series of items such as this: <item> <title>blah balh</title> <pubDate>Tue, 20 Oct 2009 </pubDate> <media:file date="today" data="example text string"/> </item> I want to use DOMDocument to get the att...
DOMDocument parsing (php)
I am parsing an xml file from an API which I have converted into a DOMDocument in php. This is mostly fine but one problem I have is when I do this: $feeditem->getElementsByTagName('extra'); as part of a forall statment and the element extra doesn't exist in one of the feeditems I am iterat...
How do you exclude the XML prolog from output?
I write $xml = new DOMDocument(); and it automatically creates <?xml version="1.0"?>. I need to NOT create it. How do i do that? One solution is to search the first ">" and strsub at the index at the first
PHP DOMDocument with åäö (UTF-8)
I got a HTML/PHP5 page with a form, then when it gets posted, it creates a XML file with the form input as data. But all åäö looks like if I had used utf8_encode() on them. I can't utf8_decode() them, because then the "service" I send the XML files to, complains that is not UTF-8 (like it should...
Walking through html searching for first level blocks
In addition to my other question about the analyzing of html, and searching for <p> and <ul>/<ol> tags this question. $in = '<p>Bit this is how far i got. What is the way to get an $out as an array containing the following: $out = array('<p>Bit's of text</p>...
Same elements from multiple files DomDocument loadHTMLFile PHP
It seems that when I have multiple files within the '/var/www/cal/attach/' directory, it only extracts the elements from the first file over and over again. Do I need to clear out the elements somehow to get this to work properly? What I'm trying to do is have the script go through multiple *.ht...
How to view DOMNodeList object's data in php
when I want to test php array I use the following code print_r($myarray); but know I want to see the data of an object my object is $xpath = new DOMXPath($doc); $myobject = $xpath->query('//*[ancestor-or-self::a]'); when I use print_r($myobject); I get that output ...
Is there a way to get all of a DOMElement's attributes?
I'm reading some XML with PHP and currently using the DOMDocument class to do so. I need a way to grab the names and values of a tag's (instance of DOMElement) attributes, without knowing beforehand what any of them are. The documentation doesn't seem to offer anything like this. I know that I ca...
DOMDocument & XPath - HTML Tag of each Node
Given the following PHP code using DOMDocument: $inputs = $xpath->query('//input | //select | //textarea', $form); if ($inputs->length > 0) { for ($j = 0; $j < $inputs->length; $j++) { $input = $inputs->item($j); $input->getAttribute('name'); // Ret...
How do I tell DOMDocument->load() what encoding I want it to use?
I search for and process XML files from elsewhere, and need to transform them with some XSLTs. No problem. Using PHP5 and the DOM library, everything's a snap. Worked fine, up till now. Today, funky characters were in the XML file -- "smart" quotes from Word, it looks like. Anyways, DOMDocument-&...
domdocument formatting
I am trying to read in the body of a certain webpage to display on a seperate webpage, but I am having a bit of trouble with it. Right now, I use the following code <?php @$doc = new DOMDocument(); @$doc->loadHTMLFile('http://foo.com'); @$tags = $doc->getElementsByTagName('body'); forea...
How to remove an HTML element using the DOMDocument class
Is there a way to remove a HTML element by using the DOMDocument class?
Disable warnings when loading non-well-formed HTML by DomDocument (PHP)
I need to parse some HTML files, however, they are not well-formed and PHP prints out warnings to. I want to avoid such debugging/warning behavior programatically. Please advise. Thank you! Code: // create a DOM document and load the HTML data $xmlDoc = new DomDocument; // this dumps out the wa...
Разбор XML с использованием PHP
У меня постоянно возникали проблемы с синтаксическим анализом XML с помощью PHP, и я не нашел "правильный путь" или, по крайней мере, стандартизированный способ синтаксического анализа файлов XML. Сначала я пытаюсь разобрать это: <item> <title>2884400</title> ...
Как я могу получить подробную информацию об ошибках при синтаксическом анализе XML, сохраняя DOM?
Я создаю веб-форму, в которой администраторы моего сайта могут добавлять XML в текстовое поле и отправлять его для хранения в таблице базы данных, но меня немного смущает лучший метод синтаксического анализа XML. Сценарий PHP должен проанализировать XML, и если есть какие-либо ошибки синтакси...
DomDocument не может добавить элемент «ссылка» для RSS-канала
Я пытаюсь создать RSS-канал на PHP с помощью DomDocument, но каждый раз пытаюсь создать узел вроде http: // domain .com скрипт не работает $oDomDocument = new DOMDocument( "1.0", "iso-8859-1" ); // Create the root now $oRootNode = $oDomDocument->createElement( "rss" ); $oRootNode->se...
PHP DOMDocument: loadHTML Файл задыхается от загадочного персонажа: RS
Использование php DOMDocument-> LoadHTMLFile ('test.html'); продолжает возвращать мне ошибку, сообщая об ошибке в содержании в строке 36. Удаляя символ за символом, оказывается, что это очевидно пустое пространство, которое было виновником. Копирование / вставка этого предложения в другом ред...
Как запретить Php DOMDocument кодировать html-объекты?
У меня есть функция, которая заменяет атрибут href привязки в строке с помощью DOMDocument Php. Вот отрывок: $doc = new DOMDocument('1.0', 'UTF-8'); $doc->loadHTML($text); $anchors = $doc->getElementsByTagName('a'); foreach($anchors as $a) { $a->setAttribute('href', 'h...
Отступы с помощью DOMDocument в PHP
Я использую DOMDocument для создания нового XML-файла, и я хотел бы, чтобы выходные данные файла были с хорошим отступом, чтобы за ним было легко следить для человека, читающего. Например, когда DOMDocument выводит эти данные: <?xml version="1.0"?> <this attr="that"><foo>...
Отладка объекта DOMDocument в PHP
Я пытаюсь отладить большой и сложный объект DOMDocument в php. В идеале было бы неплохо, если бы я мог заставить DOMDocument выводить в формате, подобном массиву. DoMDocument: $ dom = новый DOMDocument (); $ dom-> loadHTML (" Привет, мир "); var_dump ($ dom); // или что-то подобное ...
Использование DOMXPath для замены узла с сохранением его положения
Итак, на днях у меня возникла небольшая изящная идея создать вспомогательный класс для DOMDOCUMENT, который в некоторой степени имитирует способность jQuery управлять DOM строки на основе HTML или XML. Вместо селекторов css используется XPath. Например: $Xml->load($source) ->path('/...
Разбор PHP XML
Как лучше всего анализировать XML-файл в PHP? Первый Использование объекта DOM //code $dom = new DOMDocument(); $dom->load("xml.xml"); $root = $dom->getElementsByTagName("tag"); foreach($root as $tag) { $subChild = $root->getElementsByTagName("child"); // extract values and l...
Как заставить DOMDocument писать standalone = yes в PHP?
Я использую PHP5 для создания файлов XML. У меня такой код: $doc = new DOMDocument(); ... $xml_content = $doc->saveXML(); Проблема в том, что созданный XML-код начинается с корневого узла, подобного этому: <?xml version="1.0"?> Но я хочу, чтобы это было так: <?xml ve...
DOMDocument: игнорировать повторяющиеся идентификаторы элементов
Я помещаю некоторое содержимое страницы (которое было запущено через Tidy, но не обязательно, если это является источником проблем) в DOMDocument, используя DOMDocument::loadHTML. Возникают различные ошибки: ID x уже определен в Entity, строка X Есть ли способ заставить DOMDocument ...