【问题标题】:Fatal error: Uncaught TypeError: Argument 1 passed to DOMNode::appendChild() must be an instance of DOMNode, string given in致命错误:未捕获的类型错误:传递给 DOMNode::appendChild() 的参数 1 必须是 DOMNode 的实例,字符串在
【发布时间】:2023-03-30 17:26:01
【问题描述】:

我正在尝试制作一个简单的爬虫,以捕获页面的各个元素,爬虫本身为我提供了我需要的信息,但我想将其写入 XML 文件,但问题是:Fatal error: Uncaught TypeError: Argument 1 passed to DOMNode::appendChild() must be an instance of DOMNode, string given

这是我的代码:

...
$data = array(
'img-code' => $element->img,
'ean' => $eant,
'desc' => $description
);
echo $data['img-code'];

$doc = new DOMDocument();

$eanXML = $doc->createElement('Ean');
$doc->appendChild($data['ean']);

$imgXML = $doc->createElement('Img');
$doc->appendChild($data['img-code']);

$descXML = $doc->createElement('Description');
$doc->appendChild($data['desc']);

echo $doc->saveXML();
....

我想要什么输出:

<products>
<product>    
    <Ean>My ean number {$data['ean']}</Ean>
    <Img>My IMG {$data['img']}</Img>
    <Description>My Description {$data['desc']}</Description>
</product>
<product>
    <Ean></Ean>
    <Img></Img>
    <Description></Description>
</product>
</products>

【问题讨论】:

  • 你认为$eant 是什么?应该是$eanXML
  • $eant 是我的 EAN 代码。

标签: php web-crawler


【解决方案1】:

按功能要求:http://php.net/manual/en/domnode.appendchild.php

你附加到一个子节点,而不是一个字符串。

$eanXML = $doc->createElement('Ean');
$doc->appendChild($eanXML); //append to 'Ean'

【讨论】:

  • 那我怎么能把变量放到&lt;Ean&gt;VARIABLE&lt;/Ean&gt;这个:$eanXML = $doc-&gt;createElement('Ean'); $data['ean'] = $doc-&gt;appendChild($eanXML);不工作
  • 你能举一个你想要的输出的简单例子吗
猜你喜欢
  • 1970-01-01
  • 2014-01-29
  • 2013-11-23
  • 2021-04-16
  • 2018-03-28
  • 1970-01-01
  • 2021-06-14
  • 2019-11-09
  • 1970-01-01
相关资源
最近更新 更多